rethrowing subclass of RuntimeException
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).
精彩评论