Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will main thread catch exception thrown by another thread?

If I have code like this:

try
{
    Thread t = new Thread(new ThreadStart(wc.LocalRunProcess));
    t.IsBackground = true;
    t.Start();
}
catch (Exception ex)
{
    //do something with ex
}

Will the exception thrown by thread t be caught in the catch block?

like image 853
xbonez Avatar asked Feb 10 '11 21:02

xbonez


People also ask

Can you catch exception thrown by another thread?

Yes, it can be done by using Thread. UncaughtExceptionHandler. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler usingThread.

Which thread can catch an exception thrown in a thread?

if you want to handle an exception, just do it in the thread which threw it. your main thread doesn't need to wait from the background thread in this example, which actually means you don't need a background thread at all.

What happens when an exception is thrown by a thread?

An uncaught exception will cause the thread to exit. When it bubbles to the top of Thread. run() it will be handled by the Thread's UncaughtExceptionHandler. By default, this will merely print the stack trace to the console.

What happens if a thread throws an exception Python?

To catch the exception in the caller thread we maintain a separate variable exc, which is set to the exception raised when the called thread raises an exception. This exc is finally checked in the join() method and if is not None, then join simply raises the same exception.


2 Answers

No. It will not catch any exceptions in your other thread t. You will have to catch them in that thread and deal with them appropriately.

However, I believe the AppDomain's UnhandedException event will report it.

like image 183
Daniel A. White Avatar answered Oct 13 '22 08:10

Daniel A. White


Take a look at System.ComponentModel.BackgroundWorker! It has exception and cancellation handling.

like image 44
Richard Schneider Avatar answered Oct 13 '22 08:10

Richard Schneider