1

When would you want to propagate an exception to another Class/Method versus catching the Exception in the same Class/Method?

4

4 回答 4

2

You catch the exception where you have to handle it.

As a rule of thumb, you should let your exceptions bubble up, but if you don't want your subroutine to crash due to a (possibly expected) error, than you handle the exception, which normally involves logging an error and/or displaying an error message to the user.

于 2012-07-24T18:58:35.627 回答
0

The good practice is "throw early and catch late". That allows you to better understand the cause of the exception.

于 2012-07-24T18:59:33.567 回答
0

This topic is fairly broad; fortunately there are good resources already in place:

Guidelines on Exception propagation (in Java)

http://www.javacodegeeks.com/2012/04/exception-handling-guidelines-best.html

Best practices for exception management in Java or C#

于 2012-07-24T19:03:40.510 回答
0

The great majority of exceptions occuring in real-life code are not recoverable in the sense there's any meaningful code that will retry the operation or try to do it differently. The only recovery happening is aborting the current unit of work in an orderly manner—logging the exception, releasing any resources and similar.

This means that, as a first rule, you'll always want to propagate the exception towards that well-defined exception barrier that demarcates your unit of work.

If your code demands anything different than this, it is probably going to be obvious enough, so you don't need to think about it in the general.

于 2012-07-24T19:10:26.073 回答