Java:如何捕获在Method.invoke中创建的异常?
从method.invoke方法调用该方法时,我似乎无法捕获代码中的异常。如何从方法本身内部捕获它Java:如何捕获在Method.invoke中创建的异常?,java,exception-handling,invoke,Java,Exception Handling,Invoke,从method.invoke方法调用该方法时,我似乎无法捕获代码中的异常。如何从方法本身内部捕获它 void function() { try { // code that throws exception } catch( Exception e ) { // it never gets here!! It goes straight to the try catch near the invoke } } try { return method.invo
void function() {
try {
// code that throws exception
}
catch( Exception e ) {
// it never gets here!! It goes straight to the try catch near the invoke
}
}
try {
return method.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
// exception thrown in code that throws exception get here!
}
谢谢 您可以通过检查
MethodInvocationException
的getCause()
注意:您可能需要对返回的异常递归调用getCause()
,才能找到您的异常
注意:getCause()
返回一个Throwable
,您必须检查它的实际类型(例如instanceof
或getClass()
)
注意:getCause()
如果没有更多的“cause”可用,则返回null
——您已经找到抛出执行选项的基本原因
更新:
function()
中的catch()
未被执行的原因是xxxError
不是异常
,因此您的catch
不会捕获它——在function()中声明catch(Throwable)
或catch(Error)
如果您不想声明所有特定的错误——请注意,这通常是一个坏主意(如果出现OutOfMemoryError
,您打算怎么办?。您会像正常情况一样抛出异常。它在调用内部这一事实没有什么区别
public class B {
public static void function() {
try {
throw new Exception();
} catch (Exception e) {
System.err.println("Caught normally");
e.printStackTrace();
}
}
public static void main(String... args) throws NoSuchMethodException, IllegalAccessException {
Method method = B.class.getMethod("function");
Object callTarget = null;
try {
method.invoke(callTarget, args);
} catch (InvocationTargetException e) {
// should never get called.
throw new AssertionError(e);
}
}
}
印刷品
Caught normally
java.lang.Exception
at B.function(B.java:15)
... deleted ...
at B.main(B.java:26)
... deleted ...
MethodInvocationException
表示您调用的方法错误,它甚至不应该进入您的try块。从文档:
Signals that the method with the specified signature could not be invoked with the provided arguments.
编辑:如果这是Spring MethodInvokationException,Apache Velocity one会包装函数异常。无法用Exception
捕获UnsatifiedLinkError
的一个原因是UnsatifiedLinkError
不是Exception
的子类。事实上,它是Error>的子类r
您应该小心捕获错误异常。它们几乎总是表明发生了非常糟糕的事情,并且在大多数情况下不可能安全地从中恢复。例如,不满意的linkerror
意味着JVM找不到本机库……依赖于该库的任何东西都是错误的(可能)无法使用。一般来说。错误
异常应被视为致命错误。您所说的帮助我理解了这个问题。似乎我们无法使用异常捕获异常。据我所知,您需要指定确切的异常类型,以便在从invoke调用时能够捕获它。例如:catch(未满足链接错误e)而不是catch(异常e)。@user1459231-我刚刚读了详细内容。问题是xxxError
不是异常
,因此您的catch
不会捕获它——在函数()中声明catch(Throwable)
或catch(Error)
。错误和异常都扩展了Throwable,但错误不是Exception的子类,也不会被它捕获。您可以捕获Throwable来同时获取这两个,但是(我强调得不够)这是一种非常糟糕的形式,可能会在以后引起问题。特别是因为它还会捕获StackOverflowerError之类的东西,而您实际上没有能力在代码中处理它们。catch(异常e)不捕获调用内部的UnsatifiedLinkError。一般来说,异常以名称Exception结束,错误以名称Error结束。错误和异常不是一回事。