Given is an simple console application where an DivideByZeroException are thrown. To resolve is from what line and from what method instance were thrown this exception.
Example Program
private static void Main(string[] args)
{
try
{
while (true)
{
Random();
Random();
}
}
catch (Exception e)
{
Console.WriteLine("Main Catch Block ----" + Environment.NewLine + e + Environment.NewLine + "Main Catch Block ----");
throw;
}
}
private static void Random()
{
try
{
Console.WriteLine(new Random(DateTime.Now.Millisecond + 1).Next(0, 100) / new Random(DateTime.Now.Millisecond + 1).Next(0, 100));
Console.WriteLine(new Random(DateTime.Now.Millisecond + 2).Next(0, 100) / new Random(DateTime.Now.Millisecond + 1).Next(0, 100));
Console.WriteLine(new Random(DateTime.Now.Millisecond + 3).Next(0, 100) / new Random(DateTime.Now.Millisecond + 1).Next(0, 100));
}
catch (Exception e)
{
Console.WriteLine("Random Catch Block ----" + Environment.NewLine + e + Environment.NewLine + "Random Catch Block ----");
throw;
}
}
I run this program with vs2022 and .net6.0 also with vs2019 and .net Framework 4.7.2
Now I get two different results:
Vs2022 .net6.0 Stacktrace:
at ConsoleExceptionExample.Program.Random() in C:\Users\lechw\source\GitHub\LwServices\CatchMe\ConsoleExceptionExample\Program.cs:line 29
at ConsoleExceptionExample.Program.Main(String[] args) in C:\Users\lechw\source\GitHub\LwServices\CatchMe\ConsoleExceptionExample\Program.cs:line 13
This is the result what I expected and leads me to the point where the exception occur.
Vs2019 .Net Framework 4.7.2 Stacktrace:
at ConsoleExceptionsExample.Program.Random() in D:\D\Github\ConsoleExceptionsExample\ConsoleExceptionsExample\Program.cs:line 35
at ConsoleExceptionsExample.Program.Main(String[] args) in D:\D\Github\ConsoleExceptionsExample\ConsoleExceptionsExample\Program.cs:line 20
This stacktraces just points to throw method and not where the exception occur.
Why we have an different behavior? Is it possible to get same results in .net framework as in .net6.0 ?