Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to handle exception, that is thrown within catch block, in a thread. (.NET)

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?

like image 215
weilin8 Avatar asked Jul 21 '09 18:07

weilin8


2 Answers

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.

like image 185
John Saunders Avatar answered Oct 20 '22 18:10

John Saunders


What'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;
like image 43
rein Avatar answered Oct 20 '22 16:10

rein