Java异常 - 在没有try catch的情况下处理异常

时间:2011-06-05 15:37:01

标签: java exception-handling

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

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

}

但是Java中是否有任何方法可以让我在发生异常时调用一个特定的方法,而不是像上面那样编写一个catch-all方法?

具体来说,我想在抛出异常时(在我的应用程序逻辑中没有处理)在我的Swing应用程序中显示用户友好的消息。

感谢。

4 个答案:

答案 0 :(得分: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
   }
}

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

Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler() );

答案 1 :(得分:1)

try {
  // do something
   methodWithException();
}
catch (Throwable t) {
   showMessage(t);
}

}//end business method

private void showMessage(Throwable t){
  /* logging the stacktrace of exception
   * if it's a web application, you can handle eh message in an Object: es in Struts you can use ActionError
  * il it's a deskotp app, you can show a popup
  * etc., etc.
  */

}

答案 2 :(得分:0)

catch区块内显示友情讯息。

答案 3 :(得分:0)

你可以包装每个可以抛出try catch的方法

或使用getStackTrace()

catch (Throwable t) {
    StackTraceElement[] trace = t.getStackTrace();
    //trace[trace.length-1].getMethodName() should contain the method name inside the try
}

btw赶不上推荐