What's inside InvocationTargetException? Not just Exception

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: ,

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

Cheng Fang

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today