Reputation: 11
public class Confusing{
public static void main(String[] args){
Confusing cf = new Confusing();
try{
cf.confuse();
}catch(Exception e){
System.out.println("Caught exception: " + e.getMessage());
}
}
public void confuse() throws Exception{
try{
throw new Exception("First Exception");
}catch(Exception e){
throw new Exception("Second Exception");
}finally{
throw new Exception("Third Exception");
}
}
}
Why the result is Caught exception: Third Exception
?
First in try, it throws the First Exception
that is subsequently caught. Then throw the Second Exception
and also in finally Third Exception
. Why only the Third Exception
is sent back to the main?
Upvotes: 1
Views: 64
Reputation: 3302
It's right there in the Java language specification. (§11.3, Run-Time Handling of an Exception)
If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found.
If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.
Upvotes: 4