try-catch-finally结构是Java提供来处理异常的,结构大致如下:
try{
//代码执行区域
}catch(Exception e){
//异常处理区域
}finally{
//无论如何都会执行的代码区域
}
1、执行顺序
在Java程序中,有两种异常处理方法,一种是直接抛出异常(throws Exception),另一种是捕获异常内部处理(try catch finally),捕获异常的执行顺序可以用一个demo来解释
public static void main (String[] args)
{
try {
System.out.println("try");
throw new Exception("catch测试");
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
}
输出结果为:
所以可知,这里的执行顺序为:try >> catch >> finally,如果没有进入异常,那么就是try >> finally
2、当try和finally同时有返回值时,应该返回谁?
public static String try_catch_finally() {
try {
return "try的返回值";
} catch (Exception e) {
return "catch的返回值";
} finally {
return "finally的返回值";
}
}
输出结果为:
很明显,当try和finally都有返回值的时候,最终返回的是finally里的值
3、当try或者catch返回了值之后,finally又对其进行了修改,那么返回值是多少?
public static String main ()
{
String str = "Hello";
try {
return str;
}finally{
str = "World";
}
}
输出结果为:
比较奇怪,按照上面的观点,应该是返回finally里面的值的。在看了一些资料后发现,str的值在走完try代码块之后,就被内存缓存了,后面的修改无法影响到缓存中的值,但确实是返回成功了。