3

Here's 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 are executing same method at the same time. One of them sets Num1 to 0 while the other one is trying to divide by Num1 (0) at the same time. The question is why is exception thrown, why it's not caught by try catch block inside the Main method?

enter image description here

ilija veselica
  • 9,414
  • 39
  • 93
  • 147
  • 3
    Exceptions don't bubble from one thread to the thread the started it. There may not even be a guarantee that the original thread that started the one that threw an exception is even alive anymore. – vcsjones Feb 21 '14 at 15:38
  • Also, note that the IDE can sometimes (depending on settings) stop when an exception occurs even if it gets caught (not that it will get caught by the first `catch` in this case). – George Duckett Feb 21 '14 at 15:41
  • `throw ex;` is always [a bad pattern](http://stackoverflow.com/a/4553119/60761). – H H Feb 21 '14 at 17:58
  • It is a(n important) feature of the TPL to catch and marshall exceptions to the caller. Bare threads won't do that. – H H Feb 21 '14 at 17:59

1 Answers1

0

Main thread is one thread and your new thread is another thread. Those two threads does not talk to each other meaning that they are totally independent. If you want to catch the exception on your main thread there are two ways of doing it

  1. Use a backgroundworker class, the RunWorkerCompleted event will be fired on main thread, e.exception will tell you if an exception caused the thread to be aborted.

  2. Use a global catcher

add this line before your codes

Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

and

void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
//handle the exception
}
Steve
  • 11,696
  • 7
  • 43
  • 81