为什么自定义异常没有捕捉到这个? (JAVA)

Why customize Exception doesn't catch this? (JAVA)

请看下一行代码:

public void methodBla(){
     try{
         system.out.println(2/0);
     {
     catch(MyArithmeticException me){
          system.out.println("Error: My exception");
     }
     catch(Exception a){
          system.out.println("Error: general exception");
     }
}

我不明白为什么,当我试图用我的自定义 class 捕获 ArithmeticException 时:MyArithmeticException 扩展了 ArithmeticException。

 Public class MyArithmeticException extends ArithmeticException{
    public MyArithmeticException(String str){
         super("My Exception " + str);
    }
 }

MyArithmeticException 没有捕获它,它只捕获第二个 "catch"(catch(Exception a)).

谢谢 Z

很简单,因为语句 2/0 不会抛出 MyArithmeticException。它抛出 ArithmeticException 并且由于您没有捕获 ArithmeticException,它被第二个捕获捕获。

java 语言不知道您是否想从任何语言定义的异常中派生出您自己的异常类型。所以如果你需要抛出你自己的类型,你应该抓住它并重新抛出它作为 ArithmeticException:

public void methodBla(){
 try{
     try{
         system.out.println(2/0);
     catch(ArithmeticException e){
         throw new MyArithmeticException(e);
     }
 }
 catch(MyArithmeticException me){
      system.out.println("Error: My exception");
 }
 catch(Exception a){
      system.out.println("Error: general exception");
 }
}

祝你好运。

问题是会抛出算术异常。不是 "MyAritmeticException" 所以它不能被第一个 catch 子句捕获,所以它导致第二个 catch 子句。

换句话说,2/0 将抛出一个 AritmeticException,它是异常的超类,因此它不会触发 MyArithmeticException catch 块,因为那是一个子类。

如果你想自定义异常的消息你可以在catch语句中做,你可以通过Exception#getMessage()Exception#getLocalizedMessage();获取消息(两者的区别可以是找到 here)