A child thread exception is captured directly on the main thread (this method is undesirable)
Using system;using system.threading;namespace catchthreadexception{ class program { static void Main ( String[] args) { try { thread t = new Thread (() = { throw new Exception ("I am an exception thrown in a child thread! "); }); T.start (); } catch (Exception ex) { Console.WriteLine (ex. Message);}}}
The code execution results show that there is an "unhandled exception." Therefore, using this method does not catch exceptions thrown by child threads.
Two catch and handle exceptions in a child thread
Using system;using system.threading;namespace catchthreadexception{ class program { static void Main ( String[] args) { thread t = new Thread (() = = { Try { throw new Exception ("I am an exception thrown in a child thread! "); } catch (Exception ex) { Console.WriteLine ("Child Thread:" + ex.) Message); } ); T.start ();}}}
You can use this method to successfully capture and handle child thread exceptions, and the program does not crash.
Catching exceptions in three-child threads, handling exceptions in the main thread
Using system;using System.threading;namespace catchthreadexception{class Program {private delegate void Thr Eadexceptioneventhandler (Exception ex); private static ThreadExceptionEventHandler exceptionhappened; private static Exception exceptions; static void Main (string[] args) {exceptionhappened = new ThreadExceptionEventHandler (showthreadexceptio n); Thread t = new Thread (() = {try {throw n EW Exception ("I am an exception thrown in a child thread!") "); } catch (Exception ex) {onthreadexceptionhappened (ex); } } ); T.start (); T.join (); if (Exceptions! = null) {Console.WriteLine (Exceptions. Message); }} private static void Showthreadexception (Exception ex) {exceptions = ex; } private static void onthreadexceptionhappened (Exception ex) {if (exceptionhappened! = null) {exceptionhappened (ex); } } }}
Using this method can also successfully catch and handle child thread exceptions, and the program will not crash.
The benefit of this approach is that when the main thread has multiple child threads open, you can get the exceptions for all the child threads and then work together.
How to catch a child thread exception