Multithreaded exception handling

Here is a simple program:

class Program
{
    static Calc calc = new Calc();

    static void Main(string[] args)
    {
        try
        {
            var t1 = new Thread(calc.Divide);
            t1.Start();
        }
        catch (DivideByZeroException e)
        {
            //Console.WriteLine("Error thread: " + e.Message);
        }

        try
        {
            calc.Divide();
        }
        catch (Exception e)
        {
            //Console.WriteLine("Error calc: " + e.Message);
        }

    }

    class Calc
    {
        public int Num1;
        public int Num2;

        Random random = new Random();

        public void Divide()
        {
            for (int i = 0; i < 100000; i++)
            {
                Num1 = random.Next(1, 10);
                Num2 = random.Next(1, 10);

                try
                {
                    int result = Num1 / Num2;
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                Num1 = 0;
                Num2 = 0;
            }
        }
    }
}

Two threads simultaneously perform the same method. One of them sets Num1 to 0, and the other tries to divide by Num1 (0) at the same time. The question is why the exception is raised, why it did not fall into the catch catch block inside the Main method?

enter image description here

+3
source share
1 answer

The main thread is one thread, and your new thread is another thread. These two threads do not talk to each other, which means that they are completely independent. If you want to catch an exception in your main thread, there are two ways to do this.

  • backgroundworker, RunWorkerCompleted , e.exception , .

Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
//handle the exception
}
0

All Articles