如果您抛出的异常级别太低,请在上面的几次调用中捕获它们,并使用用户友好的消息将出错的原因打包为更通用和更有意义的异常,然后再次将它们抛出到可能的最高级别,在那里您停止应用程序并查看它们以某种方式(例如在标签上)给用户。
来自 Effective Java (item 61) :
It is disconcerting when a method throws an exception that has no
apparent connection to the task that it performs. This often happens
when a method propagates an exception thrown by a lower-level
abstraction. Not only is this disconcerting, but it pollutes the API
of the higher layer with implementation details. If the implementation
of the higher layer changes in a subsequent release, the exceptions
that it throws will change too, potentially breaking existing client
programs.
To avoid this problem, 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(...);
}
While exception translation is superior to mindless propagation of exceptions from lower layers, it should not be overused. Where
possible, the best way to deal with exceptions from lower layers is to
avoid them, by ensuring that lower-level methods succeed. Sometimes
you can do this by checking the validity of the higher-level method’s
parameters before passing them on to lower layers.
If it is impossible to prevent exceptions from lower layers, the next best thing is to have the higher layer silently work around these
exceptions, insulating the caller of the higher-level method from
lower-level problems. Under these circumstances, it may be appropriate
to log the exception using some appropriate logging facility such as
java.util.logging. This allows an administrator to investigate the
problem, while insulating the client code and the end user from it.
In summary, if it isn’t feasible to prevent or to handle exceptions from lower layers, use exception translation, unless the lower-level
method happens to guarantee that all of its exceptions are appropriate
to the higher level. Chaining provides the best of both worlds: it
allows you to throw an appropriate higher-level exception, while
capturing the underlying cause for failure analysis (Item 63).