我不确定如何在 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
}
现在:如果在 try 块中有要捕获的已检查异常,是嵌套 try/catch 还是在捕获 RuntimeException 后捕获这些已检查异常更好?(这可能取决于,我什至不知道这是否会发生顺便说一句)
另一件事:Error
s呢?如果我是用户,我不希望遇到意外关闭,我更希望应用程序告诉我发生了令人难以置信的错误并且没有人可以对此做任何事情,“世界末日即将来临,所以我将立即退出”。至少我会知道这不是我的错,哈哈。
顺便说一句,不知道捕获错误是否是一个好习惯......:\
在 Swing 应用程序中有更好的方法吗?