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?
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.
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.
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.
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.
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.
Take a look at System.ComponentModel.BackgroundWorker! It has exception and cancellation handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With