I’m refactoring a medium-sized WinForms application written by other developers and almost every method of every class is surrounded by a try-catch block. 99% of the time these catch blocks only log exceptions or cleanup resources and return error status.
I think it is obvious that this application lacks proper exception-handling mechanism and I’m planning to remove most try-catch blocks.
Is there any downside of doing so? How would you do this? I’m planning to:
-
To log exceptions appropriately and prevent them from propagating to the user, have an
Application.ThreadExceptionhandler -
For cases where there’s a resource that needs cleanup, leave the try-catch block as it is
Update: Using using or try-finally blocks is a better way. Thanks for the responses.
- In methods that “return-false-on-error”, let the exception propagate and catch it in the caller instead
Any corrections/suggestions are welcome.
Edit: In the 3rd item, with “return-false-on-error” I meant methods like this:
bool MethodThatDoesSomething() {
try {
DoSomething(); // might throw IOException
} catch(Exception e) {
return false;
}
}
I’d like to rewrite this as:
void MethodThatDoesSomething() {
DoSomething(); // might throw IOException
}
// try-catch in the caller instead of checking MethodThatDoesSomething's return value
try {
MethodThatDoesSomething()
} catch(IOException e) {
HandleException(e);
}
“To log exceptions appropriately and prevent them from propagating to the user, have an Application.ThreadException handler”
Would you then be able to tell the user what happened? Would all exceptions end up there?
“For cases where there’s a resource that needs cleanup, leave the try-catch block as it is”
You can use
try-finallyblocks as well if you wish to let the exception be handled elsewhere. Also consider using theusingkeyword onIDisposableresources.“In methods that “return-false-on-error”, let the exception propagate and catch it in the caller instead”
It depends on the method. Exceptions should occur only in exceptional situations. A
FileNotFoundExceptionis just weird for theFileExists()method to throw, but perfectly legal to be thrown byOpenFile().