Java Exception 异常机制(3) -- try-catch- finally块中,finally块唯一不执行的情况是什么?

lalala,之前有看到一个面试题,曰到:
try-catch- finally块中, finally块唯一不执行的情况是什么?
作为佛系博主,首些呢,就是对这道命题给予伪善的抨击
什么叫为唯一呢,什么叫唯一呢,唯一这个字在我眼里简直是对我智商的亵渎,虽然我不能像那些学霸们能给出一道数学题N种解题思路,就这道题我也想到至少想到俩种不执行情况啊?
解一: try之前异常,系统报错,当然不会执行finally

public class Math {
    public int  method01(int i,int j){//抛出异常
    int t =1/0;  // try之前异常,系统报错
        System.out.println("mehod方法开始");
        int c=0;
    try {
         c =i/j;
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("fdfd");

        }finally {

            System.out.println("finally");
            return c;
        }

解二 : try 或 catch块中,如果有exit()会使程序提前退出

public class Math {
    public int  method01(int i,int j){//抛出异常

        System.out.println("mehod方法开始");
        int c=0;
    try {
         c =i/j;
         System.exit(0);  //终止程序
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("cathc块不会执行");

        }finally {

            System.out.println("finally块不会执行");
            return c;
        }               
        }   
    }

public class TrowsDamo2 {
  public static void main(String[] args) throws Exception  {
        Math math = new Math();
        System.out.println("运算开始");
int div2 = math.method01(15, 3);//此时调用Math类的method01方法  
        System.out.println("运算结束");
        }
}

输出结果

运算开始
mehod方法开始  

引申:
如果调用math.method01(int i,int j)方法时,j 传入的值为0,程序运行到Math类中,try块第一行 c =i/j;时,会产生异常,即转入catch块处理,后续System.exit(0);就不会执行,finally块将会运行
结果如下

运算开始
mehod方法开始
cathc块不会执行
finally块不会执行
运算结束

如果以上的内容有帮到你,请一定要动动你可爱的小手指,点赞,转载,评论,帮我来个全套大保健啊~~~
敬上!

猜你喜欢

转载自blog.csdn.net/ted_cs/article/details/82421789
今日推荐