如何将错误捕获留给子类?

香脂:
public class First {
protected void method1() throws CustomException {
    int number=10/0;
    System.out.println("method 1" + number);
    throw new CustomException("Divided by zero");
}
public class Second extends First {
protected void method2() {
        method1();
    
}
public class Third extends Second {
protected void method3(){
    try {
        method2();
        }
        catch (CustomException ex)
        {
            System.out.println("Caught the exception");
            System.out.println(ex.getMessage());
        } 
}

在这段代码中,第一个引发异常,我想从第三个异常捕获(第二个将不会处理错误)。但是second的方法调用不会让我通过。我怎样才能解决这个问题?

划痕:

对于已检查的异常(不是任何异常RuntimeException),必须由调用另一个发出期望的方法的方法来处理或抛出它们。Oracle在有关异常的教程中也对此进行了更深入的说明。

此示例基于您的代码:

class Testing{
  public static void main(String[] args) {
    Third t = new Third();
    t.method3();
  }
}

它会打印:

Caught the exception
Divided by zero

添加了缺少的实现CustomException

class CustomException extends Exception{
  CustomException(){
    super();
  }
  CustomException(String message){
    super(message);
  }
}

请注意,您的代码永远都不会真正引发异常,因为首先会被零除。ArithmeticException是一个RuntimeException且因此不是受检查的异常,因此它不需要或警告任何声明。我已将其删除,因此引发了您的异常:

class First {
  protected void method1() throws CustomException {
  // will cause "java.lang.ArithmeticException: / by zero" not CustomException
  //  int number=10/0;
  //  System.out.println("method 1" + number);
    throw new CustomException("Divided by zero");
  }
} // missing end brace

您的第二个方法调用“不让我通过”的原因是因为您在的方法调用中抛出了要Exceptionmethod1其中Second调用的。因此,您需要包装对method1()try-catch块的调用,或者将其包装throws由于您“想从第三名中抓住它”,因此需要throws在方法的声明中使用它:

class Second extends First {
  // error: unreported exception CustomException; must be caught or declared to be thrown
  // protected void method2() {  // your version

  protected void method2() throws CustomException {
    method1();
  }
} // missing end brace

除添加的括号外,此保持不变:

class Third extends Second {
  protected void method3(){
    try {
      method2();
    } catch (CustomException ex) {
      System.out.println("Caught the exception");
      System.out.println(ex.getMessage());
    } 
  } 
} // missing end brace

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章