拦截异常 [英] Intercepting exceptions
问题描述
我想使用自定义异常,以便在发生任何类型的异常时出现用户友好的消息。
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.
什么是好的直截了当这样做的方式?我是否应该采取额外的预防措施以避免干扰Swing的EDT?
What's a good straightforward way of doing this? Are there any extra precautions I should take to avoid interfering with Swing's EDT?
推荐答案
例外翻译
最好不要使用对最终用户没有意义的消息污染您的应用程序,而是创建有意义的例外和消息将翻译在您的应用程序实施深处发生的异常/错误。
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.
根据@ Romain的评论,您可以使用异常(Throwable cause)构造函数跟踪较低级别的异常。
As per @Romain's comment, you can use Exception(Throwable cause) constructor to keep track of the lower level exception.
来自有效的Java第二版
,第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(...);
}
这篇关于拦截异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!