【问题标题】:How to append custom message to exception (in overrided methods which CANT throw exception)?如何将自定义消息附加到异常(在不能抛出异常的覆盖方法中)?
【发布时间】:2019-03-02 11:34:25
【问题描述】:

我知道我总是可以在 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】:

    您始终可以选择 unchecked 例外,即RuntimeException 类的子类。这些异常以及Error 的子类免于编译时检查。

    这里Parent 定义了没有throws 子句的throwException() 方法,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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2023-03-27
      • 2017-02-28
      • 2019-12-06
      • 1970-01-01
      相关资源
      最近更新 更多