Javaexception – 在没有try catch的情况下处理exception

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

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

但是Java中是否有任何方法允许我在exception发生时获取一个特定的方法,而不是像上面那样编写一个catch-all方法?

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

谢谢。

默认情况下,JVM通过将堆栈跟踪打印到System.err流来处理未捕获的exception。 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设置默认处理程序(因此抛出的任何未捕获的exception都将由此处理程序处理)。

 Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler() ); 
 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. */ 

}

catch块中显示友好消息。

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

或者使用getStackTrace()

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

顺便提一下,不推荐扔掉