Intercepting exceptions
Asked Answered
A

2

6

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?

Alien answered 4/7, 2010 at 14:14 Comment(0)
P
6

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(...);
    }
Panne answered 4/7, 2010 at 14:21 Comment(1)
+1 Just make sure you pass in your original exception to the constructor of the new one so you can see the full stack trace as well as the original cause.Shira
G
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));
}
Gnosticism answered 5/7, 2010 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.