捕获 Main 中的所有异常代码未捕获事件异常

Catch All Exceptions code in the Main is not catching events exceptions

我正在尝试放置一个 "catch all" 代码来捕获我的代码中发生的任何异常,以便将其发送到服务器。基本上,下面的代码就是我的 Main 的代码。这将创建一个带有按钮的 Jframe。当我单击其中一个按钮时,会导致崩溃(取消引用空指针)。但是,该异常未在下面的代码中捕获,而是显示在我的控制台中。

public static void main(String args[]) {

        try {


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                    JFRAME_MAIN = new MainHomePage();
                    JFRAME_MAIN.setVisible(true);

            }
        });

        } catch (Exception ex) {

          System.out.println("Exception caught");   // <--- This is not being hit
        }

}

知道为什么或如何解决这个问题吗?

谢谢

PS:我没有放置 class MainHomePage 的代码,因为它很大 class 设置布局并添加按钮及其动作侦听器。在这些听众之一中,我发生了崩溃

异常未被捕获,因为它不是由 try-catch 块内的代码抛出的。此代码不处理按钮单击,它由 ActionListener 处理。侦听器中的代码抛出异常。

invokeLater方法只是在队列中添加一个Runnable,添加Runnable的行为是成功的,因此不会产生异常。参见 this page

在您的侦听器代码中添加一个 try-catch 来处理您的按钮点击,您应该能够捕获异常 - 查找 actionPerformed 方法。

public void actionPerformed(ActionEvent e) {
    try{
        // your logic here
    }
    catch(Exception e){
        // do something to handle the exception here
    }
}

编辑(回复评论):

如果你想在一个地方处理所有未捕获的异常,你可以这样做:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("Caught exception: "+e.getClass().getName());
        // do something else useful here
    }
});

您可以将该代码放在您的 main 方法中。