Consider the below code snippets
In code snippet 1, method m1() has SQLException in throws declaration, but it is actually throwing a reference variable of type Exception. I was expecting compiler error here, since Exception is not mentioned in the throws declaration. But it compiles and prints Caught successfully
import java.sql.SQLException;
public class Snippet1{
private static void m() throws SQLException{
try{
throw new SQLException();
} catch(Exception e){
throw e;
}
}
public static void main(String[] args){
try{
m();
} catch(SQLException e){
System.out.println("Caught successfully"); //prints "Caught successfully
}
}
}
Code snippet 2 is almost same as the previous one, except that we assigned null to the exception reference variable e and then throw it. Now the compiler complains that Exception must be caught or declared to be thrown.
import java.sql.SQLException;
public class Snippet2{
private static void m() throws SQLException{
try{
throw new SQLException();
} catch(Exception e){
e = null;
throw e;
}
}
public static void main(String[] args){
try{
m();
} catch(SQLException e){
System.out.println("Caught successfully");
}
}
}
I do not understand why #1 compiles and #2 doesn't.
This is described in JDK 7 Rethrowing Exceptions with More Inclusive Type Checking
public void rethrowException(String exceptionName) throws FirstException, SecondException { try { // ... } catch (Exception e) { throw e; } }The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be
FirstExceptionandSecondException. Even though the exception parameter of the catch clause, e, is typeException, the compiler can determine that it is an instance of eitherFirstExceptionorSecondExceptionThis analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type
Exceptionin the throws clause of the method declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With