When would you want to propagate an exception to another Class/Method versus catching the Exception in the same Class/Method?
-
The answer is clear - when you don't know how to deal with this exception in the current context. – Andrew Logvinov Jul 24 '12 at 18:58
-
I think I understand. Only handle the Exception if you have to. Otherwise throw it away if you can. I'm assuming this is for the reason of backtracking through the stack to the point of the error or something like that. – Cactus BAMF Jul 24 '12 at 19:17
4 Answers
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.

- 30,851
- 12
- 72
- 100
The good practice is "throw early and catch late". That allows you to better understand the cause of the exception.

- 7,915
- 9
- 39
- 60
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
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.

- 195,646
- 29
- 319
- 436