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?