try-catch易错分析

/*
* @author YAM
*/
public class Test01 {
public static void main(String[] args) {

try {
showExce();
System.out.println("error1");
} catch (Exception e) {
System.out.println("error2");
}
System.out.println("error3");


}

public static void showExce() throws Exception{
throw new Exception();
}

}
    1. 不管有没有出现异常,finally 块中代码都会执行;

    2. 当 try 和 catch 中有 return 时,finally 仍然会执行;

    3. finally 是在 return 后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值保存起来,管 finally 中的代码怎么样,返回的值都不会改变,任然是之前保存的值),所以函数返回值是在 finally 执行前确定的;

    4. finally 中最好不要包含 return,否则程序会提前退出,返回值不是 try 或 catch 中保存的返回值。

本题中try出现异常,进入catch,而catch未产生异常,程序继续执行,输出结果为

error2

error3

 

posted @ 2022-08-01 13:10  CSU_YAM  阅读(44)  评论(0)    收藏  举报