问题描述
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在Exceptions的教程中对此也作了更深入的说明。
此示例基于您的代码:
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
您的Second
的方法调用“不会让我通过”的原因是,您在Exception
中抛出了method1
,而您在{{ 1}}的方法调用。因此,您需要将对Second
的调用包装在try-catch块中,或将其method1()
包装。由于您“想从第三名开始”,因此需要在方法的声明中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