Java异常 - 处理没有try catch的异常 [英] Java Exceptions - Handling exceptions without try catch

查看:287
本文介绍了Java异常 - 处理没有try catch的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们使用try catch块来处理异常。我知道我可以编写一个如下面的try catch块来捕获方法中抛出的任何异常。

In Java, we handle exceptions using try catch blocks. I know that I can write a try catch block like the one below to catch any exception thrown in a method.

try {
  // do something
}
catch (Throwable t) {

}

但是Java中有什么办法可以让我在异常发生时得到一个特定的方法,而不是像上面那样编写一个catch-all方法?

But is there any way in Java which allows me to get a specific method called when an exception happens, instead of writing a catch-all method like the one above?

具体来说,当我的Swing应用程序抛出异常时(我的应用程序逻辑不能处理),我想显示一个用户友好的消息。

Specifically, I would like to show a user friendly message in my Swing application when an exception is thrown (which is not handled by my application logic).

谢谢。

推荐答案

默认情况下,JVM通过将堆栈跟踪打印到System.err来处理未捕获的异常流。 Java允许我们通过提供实现 Thread.UncaughtExceptionHandler 接口的我们自己的例程来定制这个行为。


看看这篇博客文章,我写了一段时间,详细解释了这一点( http://blog.yohanliyanage.com/2010/09/know-the-jvm-1-uncaught-exception-handler/ )。


总而言之,您所要做的只是写下您的自定义逻辑:

By default, the JVM handles uncaught exceptions by printing the stack-trace to System.err stream. Java allows us to customize this behavior by providing our own routine which implements Thread.UncaughtExceptionHandler interface.

Take a look at this blog article which I wrote sometime back which explains this in detail ( http://blog.yohanliyanage.com/2010/09/know-the-jvm-1-uncaught-exception-handler/ ).

In summary, all you have to do is write your custom logic as below :

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
  public void uncaughtException(Thread t, Throwable e) {
     // Write the custom logic here
   }
}

使用上述链接中描述的三个选项中的任何一个进行设置。例如,您可以执行以下操作来设置整个JVM的默认处理程序(因此抛出的任何未捕获的异常将由此处理程序处理)。

And set it using any of the three options I have described in the above link. For example, you could do the following to set the default handler for the entire JVM (so any uncaught exception thrown will be handled by this handler).

Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler() );

这篇关于Java异常 - 处理没有try catch的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆