开发者

rethrowing subclass of RuntimeException

开发者 https://www.devze.com 2023-04-12 18:23 出处:网络
I\'m creating a general class that accepts as a parameter a list of exceptions it is willing to handle.

I'm creating a general class that accepts as a parameter a list of exceptions it is willing to handle.

public class MyClass {
  public MyClass (List<Class&l开发者_开发百科t;? extends RuntimeException>> exceptions) ...
  public execute() {
    try {
      justObj.call()
    } catch(RuntimeException e) {
      if exceptions.contains(e.getClass()) {...}
      else {throw e;}
    }

I want the thrown exception to be the original one I caught, e.g. if it was NullPointerException then I want the throw to be NullPointerException and not RuntimeException as it now.

Any idea how to achieve it ?


When you catch a RuntimeException (or any sub class), it doesn't change the type of the object/exception. If its a NullPointerException it will still be this type of object when you throw it again (as you have in your code)


It works already:

public static void main(String[] args) {
    try {
            ((ArrayList) null).get(0);
    } catch (RuntimeException e) {
        throw e;
    }
}

throws:

Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:96)


It will be - RuntimeException is just a reference to the original object, which will be whatever subclass of RuntimeException was originally thrown (e.g NullPointerException).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号