. Net main thread throws exceptions in sub-threads

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.