Intercepting exceptions

左心房为你撑大大i 提交于 2019-12-04 06:37:14

Exception Translation:

It's a good idea to not pollute your application with messages that have no meaning to the end user, but instead create meaningful Exceptions and messages that will translate the exception/error that happened somewhere deep in the implementation of your app.

As per @Romain's comment, you can use Exception(Throwable cause) constructor to keep track of the lower level exception.

From Effective Java 2nd Edition, Item 61:

[...] higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction. This idiom is known as exception translation:

   // Exception Translation
    try {
         // Use lower-level abstraction to do our bidding
         ...
    } catch(LowerLevelException e) {
         throw new HigherLevelException(...);
    }

You can use java.lang.Thread.UncaughtExceptionHandler which catches all exceptions you haven't cared for yourself

import java.lang.Thread.UncaughtExceptionHandler;

   public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {

   public void uncaughtException(Thread t, Throwable e) {
       Frame.showError("Titel", "Description", e, Level.WARNING);
       e.printStackTrace();
   }
}

register it in your app:

public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
}

and in your GUI you can use org.jdesktop.swingx.JXErrorPane from SwingX to show a nice error popup, which informs the user about exceptions.

public static void showError(String title, String desc, Throwable e,
        Level level) {
    JXErrorPane.showDialog(this, new ErrorInfo(title,
            desc, null, null, e, level, null));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!