关于 try catch finally 那点事
关于 try catch fainally yi一般的开发都不会陌生,处理运行时产生错误的一种方式
例如:
static void test() {
try {
System.out.println("try");
int i = 1 / 0;
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("fianlly");
}
}
public static void main(String[] args) {
TryCatchFinally.test();
}
运行结果显而易见
但是在工作中有一种情况要注意,当try或者catch中有return的情况下,finally中的代码段会优优先于return运行。
static String test1() {
try {
return "try";
} catch (Exception e) {
return "catch";
} finally {
System.out.println("fianlly");
}
}
public static void main(String[] args) {
System.out.println(TryCatchFinally.test1());
}
运行结果为
换到catch试试
static String test1() {
try {int i = 1 / 0;
return "try";
} catch (Exception e) {
return "catch";
} finally {
System.out.println("fianlly");
}
}
public static void main(String[] args) {
System.out.println(TryCatchFinally.test1());
}
运行结果为
小结
1、不管有没有有出现异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;
3、finally是在return后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,不管finally中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在finally执行前确定的;
4、finally中最好不要包含return,否则程序会提前退出,返回值不是try或catch中保存的返回值