X

What's inside InvocationTargetException? Not just Exception

Guest Author

Any Throwable can be wrapped inside java.lang.reflect.InvocationTargetException, as you can see from this constructor:

InvocationTargetException(Throwable target)

Even more surprisingly, a null may be inside.  This is the javadoc for getCause():


Returns the the cause of this exception (the thrown target exception,
which may be null).

So when you call InvocationTargetException.getCause(), you really need to expect 4 types of causes:


  1. null
  2. unchecked exceptions (RuntimeExceptions such as IllegalArgumentException, NullPointerException, etc)
  3. checked exceptions (e.g., NameNotFoundException, YourApplicationException)

  4. java.lang.Error (e.g., StackOverflowError, OutOfMemoryError, InternalError, UnknownError)


    try {

        helloMethod.invoke(foo);

    } catch (IllegalAccessException ex) {

       
logger.log(Level.SEVERE, "Invocation failed.", ex);


    } catch (InvocationTargetException ex) {

        Throwable cause = ex.getCause();

        if(cause == null) {

            throw new IllegalStateException(



                "Got InvocationTargetException, but the cause is null.", ex);

        } else if(cause instanceof RuntimeException) {

            throw (RuntimeException) cause;

        } else if(cause instanceof Exception) {

            logger.log(Level.SEVERE, "Invocation failed with cause: ", cause);

        } else {

            logger.log(Level.SEVERE, "Invocation failed with error: ", cause);

        }

    }



Therefore, the following may cause NullPointerException, at least in theory, though I haven't seen many people check for null:


    } catch (InvocationTargetException ex) {

        Throwable cause = ex.getCause();

        cause.printStackTrace();

The following may cause ClassCastException when casting cause to RuntimeException, since cause can be of type Error.


    } catch (InvocationTargetException ex) {

        Throwable cause = ex.getCause();

       
if(cause instanceof MyApplicationException) {

            //handle it

        } else {

            //others are not application exception, and throw them out

            throw (RuntimeException) cause;

        }

    }


technorati tags: ,

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.