Where do you like to catch exceptions and why?
I'm interested in seeing where people find it useful to put their try/catch blocks in the hope that some general patterns might emerge. I'll post my two example answers in C++ but any language is fine.
One location and reason per answer please. Thanks.
In a Delphi Windows Application, the main message handling loop for your application (i.e. at the bottom of the call stack) handles your exceptions by showing a message box. In my opinion this is the best place to handle exceptions.
By catching exceptions in your own methods for the sole purpose of showing a message box to the user, you're denying any code calling your method of knowing that an exception actually occured and that the method infact failed.
I would only handle an exception if:
I like to try and keep my exception handling code separate from my other code so I usually create a helper method that does the actual logic and the outer method just deals with exception handling. I've always thought this gives the code a clean look and makes it more readable.
Don't catch anything that you are not prepared to and able to handle.
So, have top-level exception handling in place to bomb the application the way you like on unexpected exceptions and then only catch the stuff you need (as close to where it might be occuring) to get the functionality that is needed.
And you should do only one of two things: actually do something to solve/work around the problem or rethrow a more descriptive exception that has the caught exception as its
innerException
.EDIT: If you need a
finally
block (e.g. to release something you allocated in your code) and you don't have anything useful to do with any exceptions that might pop up the same logic applies: simply don't handle them. Instead, use acatch { throw; }
to rethrow the exception to a higher level while keeping all exception info intact. (Or simply omit the catch block, which I think/hope does the same thing?)I always put a catch in main() as a catch of last resort:
Two places:
I like to catch around handlers in the controller that handle events fired from the view. If exceptions give the strong guarantee of safety this is a useful catch point because it is high level enough to report the error and the handlers are usually atomic and related to something that the user has just done so hopefully they'll be able to work out what's going on.