Intercepting exceptions

☆樱花仙子☆ 提交于 2020-01-01 09:44:13

问题


I'd like to use to a custom exception to have a user-friendly message come up when an exception of any sort takes place.

What's a good straightforward way of doing this? Are there any extra precautions I should take to avoid interfering with Swing's EDT?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/3174929/intercepting-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!