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.