繁体   English   中英

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

[英]Java: How do I catch an exception created inside the Method.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!
}

谢谢!

您可以通过检查MethodInvocationExceptiongetCause()方法来获取它的真正原因,该方法将返回从function()引发的异常

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

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

注意 :如果没有更多的“ cause”可用, getCause()将返回null -您已得出引发执行的基本原因

更新

未执行function()catch()的原因是xxxError不是Exception ,因此您的catch不会捕获它-如果您在function()声明catch(Throwable)catch(Error)不想声明所有特定的错误-请注意,这通常不是一个好主意(如果使用OutOfMemoryError您将如何处理dio?

您无法使用Exception捕获UnsatisfiedLinkError一个原因是UnsatisfiedLinkError不是Exception的子类。 实际上,它是Error的子类。

您应该小心捕获错误异常。 它们几乎总是表明确实发生了严重的故障,并且在大多数情况下,无法安全地从中恢复。 例如, UnsatisfiedLinkError表示JVM无法找到本机库...并且依赖于该库的任何内容都是(可能)无法使用的。 一般来说。 Error异常应视为致命错误。

您像往常一样抛出异常。 其内部调用的事实没有区别。

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会包装函数异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM