Directly from MSDN - Exception Handling:
Consider catching specific exceptions when you understand why it will be thrown in a given context.
You should catch only those exceptions that you can recover from. For example, a FileNotFoundException
that results from an attempt to open a non-existent file can be handled by an application because it can communicate the problem to the user and allow the user to specify a different file name or create the file. A request to open a file that generates an ExecutionEngineException
should not be handled because the underlying cause of the exception cannot be known with any degree of certainty, and the application cannot ensure that it is safe to continue executing.
Do not overuse catch
, as throwing another exception from within a catch block will reset the stack trace and cause the lost of important debugging information, as once again MSDN suggests:
Do not overuse catch. Exceptions should often be allowed to propagate up the call stack.
Catching exceptions that you cannot legitimately handle hides critical debugging information.
In the end, catching an exception should be for handling specific exceptions that you expect to occur under certain common scenario where you would like to log or to have some specific behaviour upon exception catch, otherwise simply throw
it away, as Eric Lippert
himself recommends on his blog (see Too much reuse
article).
try {
...
} catch (Exception ex) {
throw; // This does not reset the stack trace.
}
Instead of:
try {
...
} catch (Exception ex) {
throw ex; // This does reset the stack trace.
}
Finally, an Exception
does not obligatory need to offer some specificities as supplemental properties or methods or whatsoever, it is the name of it that speaks out for itself, allowing you to filter your catch upon a specific type of exception.
EDIT #1
Another interesting link about error handling on Eric Lippert's blog:
Vexing exceptions.