Retry InvocationTargetException target exception

How to throw a target exception from an InvocationTargetException. I have a method that uses reflection to invoke the invoke () method in one of my classes. However, if there is an exception in my code, I am not interested in InvocationTargetException and only want the target exception. Here is an example:

public static Object executeViewComponent(String name, Component c, HttpServletRequest request) throws Exception { try { return c.getClass() .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class) .invoke(c, request); } catch (InvocationTargetException e) { // throw the target exception here } } 

The main problem I encountered is calling throw e.getCause (); does not throw an exception, but rather throws a Throwable. Maybe I'm wrong on this?

+7
source share
5 answers
 catch (InvocationTargetException e) { if (e.getCause() instanceof Exception) { throw (Exception) e.getCause(); } else { // decide what you want to do. The cause is probably an error, or it null. } } 
+12
source

Exception#getCause returns a Throwable . If you want the compiler to think that you are throwing an Exception , you probably have to throw it.

 throw (Exception) e.getCause(); 
+2
source

You can recover any exception that you caught earlier using the throw keyword and the corresponding object that you caught:

 catch (XXXException e) { throw e; } 
0
source

Below is a detailed description, but I like to avoid reflection and casting. I do not think (but am not sure) that the Java 7 multiple-catch syntax would be useful.

 public static Object executeViewComponent(String name, Component c, HttpServletRequest request) throw KnownException_1 , KnownException_2 , ... , KnownException_n { try { return c.getClass() .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class) .invoke(c, request); } catch ( InvocationTargetException cause ) { assert cause . getCause ( ) != null : "Null Cause" ; try { throw cause . getCause ( ) ; } catch ( KnownException_1 c ) { throw c } catch ( KnownException_2 c ) { throw c } ... catch ( KnownException_n c ) { throw c } catch ( RuntimeException c ) { throw c ; } catch ( Error c ) { throw c ; } catch ( Throwable c ) { assert false : "Unknown Cause" ; } } } 
0
source

You can change the cause without explicitly declaring it.

 public static Object executeViewComponent(String name, Component c, HttpServletRequest request) throw /* known exceptions */ { try { return c.getClass() .getMethod(c.getMetaData().getMethod(), HttpServletRequest.class) .invoke(c, request); } catch (InvocationTargetException e) { // rethrow any exception. Thread.currentThread().stop(e.getCause()); } } 
-one
source

All Articles