Java 如何将自定义消息附加到异常(在不能引发异常的重写方法中)?

Java 如何将自定义消息附加到异常(在不能引发异常的重写方法中)?,java,exception,throw,Java,Exception,Throw,我知道我总是可以在try/catch块中捕获异常,并像这样抛出exception(message,e) try { //...my code throwing some exception } catch (IndexOutOfBoundsException e) { throw new Exception("Error details: bla bla", e); } 简单。但它在重写的方法中不起作用,因为它们不能用super-meth

我知道我总是可以在
try/catch
块中捕获异常,并像这样抛出
exception(message,e)

    try {
        //...my code throwing some exception
    } catch (IndexOutOfBoundsException e) {
        throw new Exception("Error details: bla bla", e);
    }
简单。但它在重写的方法中不起作用,因为它们不能用super-method-doesnt-throw抛出任何异常


那么,我现在的选项是什么呢?

您总是可以选择未选中的异常,即
运行时异常
类的子类。这些异常以及
Error
的子类不受编译时检查的约束

这里
Parent
正在定义
throweexception()
方法,该方法没有
throws
子句,
Child
类重写它,但从
catch
块抛出一个新的
RuntimeException

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