简体   繁体   English

在Main中捕获所有异常代码不捕获事件异常

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

Iam trying to put a "catch all" code to catch any exception that happens in my code so it can be sent to server. Iam尝试放入“全部捕获”代码以捕获代码中发生的任何异常,以便将其发送到服务器。 Basically, the code below is the code of my Main. 基本上,下面的代码是我的Main的代码。 This creates a Jframe with buttons. 这将创建一个带有按钮的Jframe。 When I click on one of the buttons, I am causing a crash (dereference a null pointer). 当我单击其中一个按钮时,导致崩溃(取消引用空指针)。 Howeever that exception is not being caught in the code below and instead is displayed in my consol. 但是,该异常未在下面的代码中捕获,而是显示在我的控制台中。

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
        }

}

Any idea why or how to resolve this? 知道为什么或如何解决这个问题吗?

Thanks 谢谢

PS: I didnt put the code of the class MainHomePage because it is big class that setup layout and add buttons with their action listeners. PS:我没有放入MainHomePage类的代码,因为它是设置布局并为其动作监听器添加按钮的大类。 In one of these listeners, I have the crash happening 在其中一个监听器中,我发生了崩溃

The exception is not caught because it is not thrown by the code inside your try-catch block. 不会捕获异常,因为try-catch块中的代码不会抛出该异常。 The button click is not handled by this code, it is handled by an ActionListener . 此代码未处理按钮单击,而是由ActionListener处理。 The code in the listener is throwing the exception. 侦听器中的代码引发异常。

The invokeLater method simply adds a Runnable to the queue, the act of adding that Runnable is successful and does not therefore generate an exception. invokeLater方法只是将Runnable添加到队列中,添加Runnable成功,因此不会生成异常。 See this page . 参见本页

Add a try-catch inside your listener code that handles your button click and you should be able to catch the exception - look for an actionPerformed method. 在侦听器代码中添加一个try-catch来处理按钮单击,您应该可以捕获异常-查找actionPerformed方法。

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

EDIT (responding to comment): 编辑(回复评论):

If you want to handle all uncaught exceptions in a single place you could do something like this: 如果要在一个地方处理所有未捕获的异常,可以执行以下操作:

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
    }
});

You would place that code inside your main method. 您可以将该代码放入您的main方法中。

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

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