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

Mas*_*Man 3 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.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
  // exception thrown in code that throws exception get here!
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Att*_*ila 5

您可以MethodInvocationException通过检查getCause()将返回从function()

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

注意getCause()返回 a Throwable,您必须检查其实际类型(例如instanceofgetClass()

getCause()回报null,如果没有更多的“事业”可-你在execption的基本原因抛出已抵达

更新

catch()infunction()没有被执行的原因是它xxxError不是 an Exception,所以你catch不会抓住它——如果你不想声明所有特定的错误,就声明catch(Throwable)or catch(Error)infunction()如果你不想声明所有特定的错误——请注意,这通常是一个坏主意(你打算用 dio 做OutOfMemoryError什么?

  • @ user1459231 - 我刚刚阅读了细则。问题是`xxxError` 不是一个`Exception`,所以你的`catch` 不会捕捉到它——在`function()` 中声明`catch(Throwable)` 或`catch(Error)`。 (2认同)