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.
(Before I begin: I am a Java guy)
What I recommend:
handle(Exception e)
method and release that to the team initially and ensure that everyone uses it to handle exceptions. Based on changing exception handling scenarios, keep adding overloaded 'handle' methods later on so that only the handler need to be modified.I try to catch ONLY those exceptions that I can deal with.
I HATE code like this:
What I especially hate is that what this usually does is to abort the thread anyway, because three lines later there will be an access to i that will assume that i != null.
Then you will read your stacktrace and scroll and scroll and scroll the log til you find the first signifant mistake that made everything else fall apart.
I wish Java didn't force me to catch Exceptions that I cannot deal with, anyway. But what I can do is this:
And I declare a lot of "throws" in my function definitions.
I am still dreaming of the day where Eclipse will automatically open a Debugger in the correct line when it will get an uncaught exception. That day, my method will open the correct line.
In other languages, like Smalltalk, I catch only the errors that I can handle. And I happily throw uncaught exceptions when the input does not meet my expectations.
The idea is that I don't want the error to be logged or documented. I want it fixed.
In C# and Java I prefer to not catch exceptions at all. If I can't avoid it, I rethrow a RunTime-exception immediately.
I'll always use the greediest catch block that has the largest scope needed, but always with the most specific exception-type possible. Since the outcome of the catch block is another throw in 99.99% of the cases, I try to keep the full method within the try block.