具有多个catch块的异常处理 [英] Exception Handling with Multiple catch block

查看:127
本文介绍了具有多个catch块的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的程序。

  try {
int a = 1/0;
}
catch(Exception e){
system.out.println( Exception block + e);
}
catch(ArithmeticException e){
system.out.println( Inside ArithmeticException block);
}
最终{
system.out.println( Inside Final block);
}

在上面的程序中,我有两个catch块,一个finally块。 p>

将执行哪个catch块?因为我先定义了父级catch块。那么会导致错误吗?谁能帮我吗?



我假设将执行 ArithmeticException和Final代码块。

解决方案

捕获 Exception 类不会产生任何错误。但是,不建议这样做。



在这种情况下,例外 捕获块将首先执行,然后最终执行 块。



如果您希望<$应该执行c $ c> ArithmeticException 块,将此块放在 Exception catch 块之前。



更新代码-

 试试{
int a = 1/0;
}
catch(ArithmeticException e){
System.out.println( Inside ArithmeticException block);
}
catch(Exception e){
System.out.println( Exception block + e);
}
最终{
System.out.println( Inside Final block);
}


Here is my program.

try {
    int a = 1/0;
}
catch(Exception e) {
    system.out.println("Exception block"+e);
}
catch(ArithmeticException e) {
    system.out.println("Inside ArithmeticException block");
}
finally {
    system.out.println("Inside Finally block");
}

In the above program i have two catch blocks and one finally block.

Which catch block will execute? Because I define the parent catch block first. So it leads to an error? Can any one help me?

I assumed that "ArithmeticException and Finally block will be executed"

解决方案

Catching Exception class will not give any error. However, it is not recommended.

In this case, Exception catch block will execute first and then finally block will execute.

If you want that your ArithmeticException block should execute, put this block before Exception catch block.

Update code -

    try{
        int a = 1/0;
    }        
    catch(ArithmeticException e){
        System.out.println("Inside ArithmeticException block");
    }
    catch(Exception e) {
        System.out.println("Exception block"+e);
    }
    finally{
        System.out.println("Inside Finally block");
    }

这篇关于具有多个catch块的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆