问题
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