-1

请看下面的代码行:

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");
     }
}

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

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

MyArithmeticException 没有捕捉到它,它只捕捉到第二个“catch”(catch(Exception a))。

谢谢Z

4

2 回答 2

2

这很简单,因为该语句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");
 }
}

祝你好运。

于 2016-01-31T12:07:36.983 回答
0

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

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

如果您想自定义异常的消息,您可以在 catch 语句中执行此操作,您可以通过Exception#getMessage()or获取消息Exception#getLocalizedMessage();(两者的区别可以在这里找到)

于 2016-01-31T12:12:13.457 回答