Java异常 - 不使用try catch处理异常

18
在Java中,我们使用try catch块来处理异常。我知道可以像下面这样编写try catch块来捕获方法中抛出的任何异常。
try {
  // do something
}
catch (Throwable t) {

}

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

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

谢谢。


你不应该捕获 Throwable,而应该捕获 Exception。Throwable 包括 Error 及其子类,通常无法处理。 - Dónal
1
我想通过Swing向用户提供友好的错误消息,这就是为什么我包含了Throwable的原因。即使出现错误,我也希望我的用户知道发生了什么事情,而不仅仅是将其记录到日志文件中。 - Devanath Rao
4个回答

32

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
   }
}

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() );


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 the message in an Object: es in Struts you can use ActionError
   * if it's a desktop app, you can show a popup
   * etc., etc.
   */
}

我正在寻找一种替代方案,以避免在我的应用程序中到处编写try-catch块。此外,我正在寻找更好的替代方案来处理主方法中的单个catch-all块。目前,我似乎必须在每个线程中编写一个catch-all块来处理这个问题。 - Devanath Rao

0
catch块中显示友好的消息。

我正在寻找一种替代方案,以避免在我的应用程序中到处编写try-catch块。此外,我正在寻找一个更好的替代方法来处理主方法中的单个catch-all块。目前,我似乎必须在每个线程中编写一个catch-all块来处理这个问题。 - Devanath Rao

0
你可以在每个可能抛出异常的方法中使用try catch语句包装起来,
或者使用getStackTrace()
catch (Throwable t) {
    StackTraceElement[] trace = t.getStackTrace();
    //trace[trace.length-1].getMethodName() should contain the method name inside the try
}

顺便提一下,在编程中不建议捕获 Throwable 异常


我正在寻找一种替代在每个地方编写try-catch块的方法,就像我在问题中提到的那样。另外,我想通过Swing向用户提供友好的错误消息。这就是为什么我包括Throwable的原因。即使发生错误,我也希望我的用户知道这件事,而不仅仅是进入我的日志文件。 - Devanath Rao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接