What's your opinion in handling exceptions within a thread's execution? More specifically, what if the exception is thrown inside catch block of an try-catch clause? And what happen to the thread if the exception is unhandled?
views:
715answers:
5What's your opinion in handling exceptions within a thread's execution?
You should handle exceptions whenever possible and whenever you expect exceptions. Clarification: I totally agree with John that you should not handle exceptions everywhere - only where you can do something about them. However, you should never let an exception go unhandled in a thread as this will cause serious problems. Have a root exception handler and let your thread die gracefully (after logging the problem etc...)
More specifically, what if the thread is thrown inside catch block of an try-catch clause?
Did you mean: What if the exception is thrown within the catch block? Well, then it goes unhandled by the current try-catch block. It's best not to put too much processing in a catch block to avoid this situation as much as possible.
And what happen to the thread if the the the thread is unhandled?
Did you mean: What happens to the thread if the exception is unhandled? It dies.
And as Ben mentioned:
An uncaught exception in a thread triggers an UnhandledException in the thread's AppDomain. You can watch for these by adding an event handler:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
An uncaught exception in a thread triggers an UnhandledException in the thread's AppDomain. You can watch for these by adding an event handler:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
I have to disagree with ren, or at least with what it sounds like he meant.
Only handle exceptions if you can actually handle them. Only if you can do something about what went wrong, or add information. Don't handle them just because you can.
try {
// ..
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
The above is very bad. First, you don't display the entire exception, but only the Message. Second, you let things continue, and you don't know what state the process is in.
Unhandled exceptions in a thread cause your process to die, and die with an unhelpful message in your event log.
Having top level exception handlers in every thread that log (and maybe re-throw) is a good practice, as is installing an appdomain exception handler as the other responses mention.
If you think you can handle an exception, you should catch it. All other exceptions that can not be dealt with should bubble up to the surface of the stack where if along the way no appropriate handler is found, will let the thread die.
You should not write any code in a catch block that could throw another exception, but if you need to you could nest another try catch block around it.