I have following 2 code snippets and I am wondering what makes java compiler (In Eclipse with Java 7) to show error for 2nd snippet and why not for 1st one.
Here are the code snippets:
snippet 1
public class TestTryCatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(get());
}
public static int get(){
try{
System.out.println("In try...");
throw new Exception("SampleException");
}catch(Exception e){
System.out.println("In catch...");
throw new Exception("NewException");
}
finally{
System.out.println("In finally...");
return 2;
}
}
}
snippet 2
public class TestTryCatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(get());
}
public static int get(){
try{
System.out.println("In try...");
throw new Exception("SampleException");
}catch(Exception e){
System.out.println("In catch...");
throw new Exception("NewException");
}
// finally{
// System.out.println("In finally...");
// return 2;
// }
}
}
In eclipse, snippet1 shows to add 'SuppressWarning' for finally block, but in snippet2, it shows to add 'throws or try-catch' block for the throw statement in catch block.
I had a detailed look at following questions, but they didn't provide any concrete reason for this.
Best Answer
The
finally
block should always execute. This is the main reason. The exception is thrown in thecatch
block butreturn
statement executed in thefinally
block masks exception. Either removefinally
block or movereturn
statement out of thefinally
block.