Java:在 GUI 中显示崩溃,但抑制警告
对于桌面应用程序,当程序崩溃时在 GUI 上查看堆栈跟踪非常有用。我在 Java 中实现了这一点,方法是将 System.err 替换为我自己的错误处理程序,该处理程序将所有错误消息重定向到 GUI 组件和文本文件。
问题:相当多的库(例如 Apache POI)在发生崩溃时不仅仅写入 System.err,它们还输出简单的警告消息。这会导致不必要地弹出崩溃窗口。 所以我的问题是,有人知道如何(1)在程序崩溃时显示堆栈跟踪,而(2)在出现警告消息时不显示它吗?
[编辑] 我的 GUI 是用 SWT 编写的。
For desktop apps, it's useful to see the stacktrace on the GUI when the program crashes. I implemented this in Java by replacing System.err with my own error handler, which redirects all error messages to a GUI component and a text file.
The problem: Quite a few libraries out there (e.g. Apache POI) don't just write to System.err when a crash occurs, they also output simple warning messages. This causes the crash window to pop up unnecessarily.
So my question is, does anybody know how to (1) show the stacktrace when the program crashes, while (2) not showing it in case of warning messages?
[Edit] My GUI is written in SWT.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以安装自己的异常处理程序。这里解释了 Swing 的一项技术: http ://ruben42.wordpress.com/2009/03/30/捕捉-all-runtime-exceptions-in-swing/。 Eric Burke 还有关于这个主题的好文章。另一种通用技术是使用
Thread.setDefaultUncaughtExceptionHandler
,当线程因异常而死亡时调用(根据第一篇引用的文章中的注释,Swing线程不会死亡,因此设置未捕获的异常处理程序不适用于 Swing,但 Eric 的文章使用了此技术)。然后,您的异常处理程序可以显示错误、记录错误或执行任何您想要的操作,而无需关心使用标准输出/错误流的其他代码。
You can install own exception handlers. One technique for Swing is explained here: http://ruben42.wordpress.com/2009/03/30/catching-all-runtime-exceptions-in-swing/. Eric Burke also has nice article on this topic. Another general technique is using
Thread.setDefaultUncaughtExceptionHandler
, which is called when thread dies due to exception (according to comments in the first referenced article, Swing thread doesn't die, so setting uncaught exception handler doesn't work for Swing, but Eric's article uses this technique).Your exception handler can then display error, log it, or do anything you want, without caring about other code using standard output/error streams.
我认为你从错误的角度来处理这个问题。当出现异常时,您应该弹出一个对话框,而不仅仅是当有输出到 System.err 时。 System.err 更像是一个日志实用程序。
对于所有已检查的异常,您应该在代码中逐案处理它们。要么弹出一个对话框,记录它们,要么忽略它们(但在这种情况下,请确保这样做确实安全)
要捕获任何剩余的未经检查的异常,您可以执行以下操作: http://www.javaspecialists.eu/archive/Issue081.html,以确保您得到这些。
I think you're approaching the problem from the wrong angle. You should be popping up a dialog when there are exceptions, not just when there is output to System.err. System.err is more like a logging utility.
For all checked exceptions, you should handle them case by case in your code. Either pop up a dialog, log them, or ignore them (but in that case, be sure that it's really safe to do so)
To catch any remaining unchecked exceptions, you can do something like this: http://www.javaspecialists.eu/archive/Issue081.html, to make sure that you're getting those.