1、正常执行顺序:try → catch → finally → 其他代码
2、try,catch和finally和其他代码的执行条件:
先执行try。
只要try中有异常,catch就会执行;
finally总会执行;
其他代码:
如果finally中没有return:其他代码会执行;
如果finally中有return:其他代码不会执行;
注意:finally中的语句会在return之前执行,但返回值是在执行finally中的语句之前确定的。
注:【强制】不要在 finally 块中使用 return。 说明:finally 块中的 return 返回后方法结束执行,不会再执行 try 块中的 return 语句。 ——阿里开发手册。
例:
public class Test
{
public static int aMethod(int i)throws Exception
{
try{
return i / 0;
}
catch (Exception ex)
{
throw new Exception("exception in a Method");//捕获异常,向上抛出
} finally{
System.out.printf("finally");
}
}
public static void main(String [] args)
{
try
{
aMethod(10);
}
catch (Exception ex)
{
System.out.printf(ex.getMessage());//打印异常信息
System.out.printf("exception in main");
}
System.out.printf("finished");
}
}
代码执行结果为:
finally
exception in a Method
exception in main
finished