我知道我总能在try/catch
区块中捕获异常并像这样抛出Exception (message, e)
try {
//...my code throwing some exception
} catch (IndexOutOfBoundsException e) {
throw new Exception("Error details: bla bla", e);
}
简单。但它在重写方法中不起作用,因为它们不能抛出任何超级方法抛出的异常。
那么,我现在的选择是什么?
您可以随时选择未经检查的异常,即RuntimeException
类的子类。这些异常以及Error
的子类免于编译时检查。
在这里Parent
定义throwException()
方法,没有throws
条款和Child
类覆盖它,但从RuntimeException
块抛出一个新的catch
。
class Parent{
public void throwException(){
System.out.println("Didn't throw");
}
}
class Child extends Parent{
@Override
public void throwException(){
try{
throw new ArithmeticException("Some arithmetic fail");
}catch(ArithmeticException ae){
throw new RuntimeException(ae.getMessage(), ae);
}
}
}