有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果方法是用invoke启动的,异常不会导致崩溃

出于某种原因,如果通过invoke()调用方法,则它抛出的未捕获异常不会导致崩溃。但是,它确实退出了该方法。invoke是否运行另一个线程(因为异常只是使线程崩溃,对吗?),如果是这样的话,有没有一种方法可以发送异常或其他什么

下面是一个简单的例子:

import java.lang.reflect.InvocationTargetException;

public class Main {
    public static void main(String[] args) {
        try {
            Class.forName("Main").getMethod("thrower").invoke(null);
        }
        catch (IllegalAccessException e) {}
        catch (IllegalArgumentException e) {}
        catch (ClassNotFoundException e) {}
        catch (NoSuchMethodException e) {}
        catch (InvocationTargetException e) {}
        catch (SecurityException e) {}
    }
    public static void thrower() {
        throw new RuntimeException();
    }
}

共 (2) 个答案

  1. # 1 楼答案

    ^{}文档:

    @exception InvocationTargetException if the underlying method throws an exception.

    您正在捕获一个^{},它将被抛出^{}原因:

    catch (InvocationTargetException e) {
        final Throwable cause = e.getCause();
        // cause.getClass().getName() = java.lang.RuntimeException
    }
    
  2. # 2 楼答案

    它不是在单独的线程中运行的。从thrower抛出的RuntimeException实际上在反射调用期间被InvocationTargetException包装,稍后被不做任何操作的代码捕获

    有关InvocationTargetException的信息,请参见Javadoc

    InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "target exception" that is provided at construction time and accessed via the getTargetException() method is now known as the cause, and may be accessed via the Throwable.getCause() method, as well as the aforementioned "legacy method."