One of the experience summary of exception handling: Do not throw invocationtargetexception directly (turn http://olylakers.iteye.com/blog/1137371)
In the recent period of work, accumulated a few exceptions to deal with the experience, afraid of a long time on the forgotten, so write down this document, and then summarize and review later.
1. When the method is executed by reflection, such as Method.invoke (), if the body of the method being reflected by the reflection throws a exception, the exception will be wrapped InvocationTargetException re-thrown, the following is the source code inside the JDK:
Public object Invoke (Object obj, object ... args) throws <span style= "color: #ff0000;" >IllegalAccessException</span>, IllegalArgumentException, invocationtargetexception { ........... Omitted here ... }
For example, the reflection method throws a Nullpointexception, The Method.invoke method throws the InvocationTargetException, not the nullpointexception, as shown in the following example, the InvocationTargetException is thrown here.
But invocationtargetexception too broad, in trouble shouting time, can not give people very intuitive information, so when dealing with the reflection method anomalies, We need to extract and re-throw this invocationtargetexception targetexception, because this is the exception that really helps our parser bugs:
Public classinvokeexception {@SuppressWarnings ("NULL") Public voidtestexception () {String nullstring=NULL; Nullstring.tostring (); } Public Static voidMain (string[] args)throwsThrowable {//TODO auto-generated Method Stub Try{invokeexception invokeexception=Newinvokeexception (); Method Method= Invokeexception.getclass (). GetMethod ("TestException"); Method.invoke (invokeexception); }Catch(Exception e) {if(Einstanceofinvocationtargetexception) { //throw ((InvocationTargetException) e). Gettargetexception (); The Throwable.getcause () method is today the preferred means of obtaining this information.e.getcause ()}Else{ Throwe; } } } }
Java Basic Exception