First, let's look at a piece of C # code. After running the code, we can find that the main thread cannot catch exceptions thrown in the subthread through try {} catch.
Code Class Program
{
Static void Main (string [] args)
{
Try
{
System. Threading. Thread thread = new System. Threading. Thread (new Program (). run );
Thread. Start ();
}
Catch (Exception ex)
{
Console. WriteLine (ex. Message );
}
Thread. Sleep (1000 );
}
Public void run ()
{
Throw new Exception ();
}
}
Why?
First, you need to understand the exception implementation mechanism: the exception implementation mechanism is heavily dependent on the thread stack. Each thread has a stack. After the thread starts, it installs some exception handling frames on the stack and forms a linked list structure. When an exception occurs, the linked list can be used for Stack rollback, if you have not installed it yourself, it may jump directly to the end of the linked list, which may be a default processing frame provided by the CRT. A dialog box pops up prompting a memory error for a specific address, and then confirm the debugging, cancel closing.
Therefore, exceptions cannot be exchanged between threads.
However, in actual program design, exceptions of sub-threads are involved. How can this problem be solved?
Code Class Program
{
Private delegate void ExceptionHandler (Exception ex );
Private static ExceptionHandler exception;
Private static void ProcessException (Exception ex)
{
Console. WriteLine (ex. Message );
}
Static void Main (string [] args)
{
Exception = new ExceptionHandler (ProcessException );
System. Threading. Thread thread = new System. Threading. Thread (new Program (). run );
Thread. Start ();
Thread. Sleep (1000 );
}
Public void run ()
{
Try
{
Throw new Exception ();
}
Catch (Exception ex)
& Nb