as with multi-catch, you shouldnot be assigning a new value to catch parameter. The difference b/w this and multi-catch is where the compiler error occurs. For multi-catch, the compiler error will occur on the line where we attempt to assign a new value to the parameter, whereas here, the compilation error on the line where we throw e.
but I am not encountering such exception, my code is :
I am running this on JDK 8, is this the reason for my problem ??
Ankit Garg wrote:
When using a reference variable, compiler always looks at the declaration. So the compiler knows ex is of type Exception but the throws clause is incompatible with it...
I was expecting the same reason, but got stuck at a point
look at this :
correct me if I am wrong in my //comment statement, and if not, then why not the compiler is not smart enough to find that exception is of type Exception and cannot be thrown by this method (as is finds in other cases) ..!!
Pushpender the compiler doesn't care what an object is initialized with after the initialization. It only considers the declared type of the variable. It's the same for all variables:
In the above code too the compiler doesn't know what obj is initialized with String so explicit cast is needed to assign it to a String variable. The code that you have in the previous post won't compile on older versions of Java. The new ability of the compiler to detect what type of exception is caught ends if you re-initialize the caught exception variable yourself...