publicclassReflect{ publicvoidrun(int i)throws ZeroException { A b = new A(); a.run(i); } }
classA{ publicvoidrun(int i)throws ZeroException { if (i < 0) { thrownew ZeroException("Parameter must be greater than zero!"); } System.out.println("Param: " + i); } }
Receive uncaught exception here. java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.zzj.test.reflect.Test.main(Test.java:11) Caused by: me.redneno.test.reflect.ZeroException: Parameter must be greater than zero! at me.redneno.test.reflect.A.run(Reflect.java:13) at me.redneno.test.reflect.Reflect.run(Reflect.java:6) ... 5 more
还可以直接打印目标异常
1 2 3 4 5 6 7
... catch (InvocationTargetException e) { System.out.println("Receive uncaught exception here."); Throwable t = e.getTargetException(); // Get target exception t.printStackTrace(); } ...
输出
1 2 3 4 5 6 7 8 9
Receive uncaught exception here. com.zzj.test.reflect.ZeroException: Parameter must be greater than zero! at me.redneno.test.reflect.A.run(Reflect.java:13) at me.redneno.test.reflect.Reflect.run(Reflect.java:6) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at me.redneno.test.reflect.Test.main(Test.java:11)