Dev*_*Rao 15 java exception-handling
在Java中,我们使用try catch块处理异常.我知道我可以编写一个类似下面的try catch块来捕获方法中抛出的任何异常.
try {
// do something
}
catch (Throwable t) {
}
Run Code Online (Sandbox Code Playgroud)
但是Java中是否有任何方法允许我在异常发生时获取一个特定的方法,而不是像上面那样编写一个catch-all方法?
具体来说,我想在抛出异常时(在我的应用程序逻辑中没有处理)在我的Swing应用程序中显示用户友好的消息.
谢谢.
Yoh*_*age 28
默认情况下,JVM通过将堆栈跟踪打印到System.err流来处理未捕获的异常.Java允许我们通过提供实现Thread.UncaughtExceptionHandler接口的自己的例程来自定义此行为.
看一下我之后写的这篇博客文章,详细解释了这一点(http://blog.yohanliyanage.com/2010/09/know-the-jvm-1-uncaught-exception-handler/).
总之,您所要做的就是编写自定义逻辑,如下所示:
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
// Write the custom logic here
}
}
Run Code Online (Sandbox Code Playgroud)
并使用我在上面链接中描述的三个选项中的任何一个来设置它.例如,您可以执行以下操作来为整个JVM设置默认处理程序(因此抛出的任何未捕获的异常都将由此处理程序处理).
Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler() );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18481 次 |
| 最近记录: |