gpt4 book ai didi

Java:如何捕获在 Method.invoke 中创建的异常?

转载 作者:行者123 更新时间:2023-12-03 21:31:25 25 4
gpt4 key购买 nike

当从 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.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
// exception thrown in code that throws exception get here!
}

谢谢!

最佳答案

您可以通过检查 getCause() 方法来获取 MethodInvocationException 的真正原因,该方法将返回 function() 抛出的异常

注意:您可能需要在返回的异常上递归调用 getCause() 才能到达您的异常。

注意:getCause() 返回一个 Throwable,您必须检查它的实际类型(例如 instanceofgetClass())

注意:如果没有更多“原因”可用,getCause() 将返回 null —— 你已经找到了抛出异常

更新:

function()中的catch()没有被执行的原因是xxxError不是Exception,所以你的 catch 不会捕获它——在 中声明 catch(Throwable)catch(Error) function() 如果您不想声明所有特定错误 - 请注意,这通常是个坏主意(您打算用 OutOfMemoryError 处理什么?

关于Java:如何捕获在 Method.invoke 中创建的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11054833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com