What is the order of execution in try,catch and finally
This question already has an answer here:
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
finally
always executes. If there is a return
in try
, the rest of try
and catch
don't execute, then finally
executes (from innermost to outermost), then the function exits.
first of all you need to go for documentation and understand the concept correctly you can refer these documentation
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
here on stackoverflow no one should explain because this site not a toturial purpose basically.
Normally order execution order of try-catch-finally
is first try
, then if exception
trows and caught will execute
the catch
. If exception caught or not finally
will always execute.
If return
in your try
, execution in try
will stop there and will execute finally
. if exception
throws and caught before that return
normal execution order will follows.
Let's run following code
public static void main(String[] args) {
String[] arr=getInfo();
for(String i:arr){
System.out.println(i);
}
}
public static String[] getInfo(){
String[] arr=new String[3];
try {
arr[0]="try";
return arr;
}catch (Exception e){
arr[1]="catch";
return arr;
}finally {
arr[2]="finally";
return arr;
}
}
Out put
try // return in try
null
finally // returning value in finally.
Now this out put explain the every thing you want. finally
runs while there is a return
in try
.
If there a System.exit(0)
in your try
, finally
is not going to execute.
上一篇: 终于总是被叫?