在Swing GUI中处理异常

tmh*_*tmh 6 java swing exception-handling exception

我不确定如何管理GUI中的异常; 我的目标是让用户知道是否出现问题,显示可理解的消息.

我想做这样的事情:

// I'm inside an actionPerformed() method
try {
    // do whatever I have to do here
} catch (KnownBusinessException1 e) {
    // inform the user and do something;
    // most times simply inform the user that it wasn't possible to complete the
    // operation and remain in the same window instead of moving forward.
} catch (KnownBusinessException2 e) {
    // just as above
} catch (KnownDataAccessException1 e) {
    // just as above
} catch (KnownDataAccessException2 e) {
    // just as above
} catch (RuntimeException e) { // I want to catch any other unexpected exception,
// maybe NPE or unchecked IllegalArgumentExceptions and so on
    // something went wrong, I don't know where nor how but I will surely inform the user
}
Run Code Online (Sandbox Code Playgroud)

现在:如果在try块中有被检查的异常捕获,嵌套try/catch或捕获RuntimeException后捕获这些已检查的异常会更好吗?(这可能取决于,我甚至不知道这是否会发生顺便说一句)

另一件事:Errors怎么样?如果我是一个用户,我不想经历意外关机,我更倾向于该应用程序告诉我,某些事情发生了令人难以置信的错误,没有人能对此做任何事情,"世界末日即将到来,所以我将立即退出".至少我会知道那不是我的错.

顺便说一下,不知道抓错是不是一个好习惯......:

在Swing应用程序中有更好的方法吗?

lba*_*scs 10

我认为最好是明确捕获所有已检查的异常,并为其余的安装未捕获的异常处理程序.请参阅:如何检测何时在Java中全局抛出异常?

这是我使用Thread.setDefaultUncaughtExceptionHandler的方式:

public static void setupGlobalExceptionHandling() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            handleException(e);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意,许多SO帖子中提到的EDT线程的"sun.awt.exception.handler"技巧不是必需的,并且在Java 7中不起作用.对于Java 7,只需使用标准的Thread.setDefaultUncaughtExceptionHandler,如上所述.当然,如果您使用这两种机制来注册异常处理程序,则代码将适用于所有版本.

顺便说一句,如果抛出未捕获的异常(但您的应用程序可能仍处于不一致状态),EDT线程会自动重启,请参阅:EDT和运行时异常


Bhe*_*ung 0

如果try块中有要捕获的检查异常,那么嵌套一个try/catch更好还是在捕获RuntimeException之后捕获这些检查异常更好?(这可能取决于,我什至不知道这是否会发生顺便说一句)

就像你说的那样,这取决于在捕获异常后执行 try 块中的其余代码是否有意义。如果不是,那么嵌套 try/catch 块就没有意义。