如何将自定义消息附加到异常(在CANT抛出异常的覆盖方法中)?

问题描述 投票:1回答:1

我知道我总能在try/catch区块中捕获异常并像这样抛出Exception (message, e)

    try {
        //...my code throwing some exception
    } catch (IndexOutOfBoundsException e) {
        throw new Exception("Error details: bla bla", e);
    }

简单。但它在重写方法中不起作用,因为它们不能抛出任何超级方法抛出的异常。

那么,我现在的选择是什么?

java exception throw
1个回答
2
投票

您可以随时选择未经检查的异常,即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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.