how to handle exception if finally follows try block
If i put only finally without catch block how exception will be h开发者_运维问答andled
The exception will be passed up the call stack, as if the your try block did not exist, except the code in the finally will be executed.
Some example code
try {
// an exception may be thrown somewhere in here
}
finally {
// I will be executed, regardless of an exception thrown or not
}
Your exception will not be caught but the 'finally' block will be called and executed eventually. You can write a quick method as below and check it out :
public void testFinally(){
try{
throw new RuntimeException();
}finally{
System.out.println("Finally called!!");
}
}
If i put only finally without catch block how exception will be handled
In that situation, the exception will not caught or handled. What happens, depends on what happens in the finally
clause.
- If the statement sequence in the
finally
clause completes "normally", the original exception will continue propagating. - If the statement sequence in the
finally
clause completes "abruptly" for some reason then the entiretry
statement terminates for that reason. Abrupt terminations include throwing an exception, executing areturn
,break
orcontinue
. In this case, the original exception is lost without ever being "handled".
This has some rather interesting consequences. For example, the following squashes any exceptions thrown in the try block.
public void proc () {
try {
// Throws some exception
} finally {
return;
}
}
The details of try
statements with finally
clauses are set out in JLS 14.20.2
精彩评论