We all know about latest changes made in try-catch block in Java 7.
My query is - If we define catch block as shown below
As we know every reference variable in Java must have a Type associated with it.
Now at compile time, what Type is assigned to 'e' variable by Java Compiler ? Is it SQLException ? Is it IOException ? Or something else?
The answer will doubtless be in the Java Language Specification.That will of course print the runtime type of the Exception, vizFileNotFoundException.
I am sure it will make no difference whether you are catching checked or unchecked Exceptions.
The declared type of an exception parameter that denotes its type with a single class type is that class type.
The declared type of an exception parameter that denotes its type as a union with alternatives D1 | D2 | ... | Dn is lub(D1, D2, ..., Dn) (§22.214.171.124).
An exception parameter of a multi-catch clause is implicitly declared final if it is not explicitly declared final.
and "lub" sounds like "least upper bound", as one would guess.
Handling More Than One Type of Exception
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Consider the following example, which contains duplicate code in each of the catch blocks:
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.