throw, reissues the error with the same StackTrace as before. issues exactly the same error as before.
But if you use throw ex, it still issues the same error as before, but with one difference, it resets StackTrace! For example, in the following code, in the DoSomething method, we perform a split-zero operation that causes an error (we used throw ex). Then, in the main method, when it enters the catch method and displays StackTrace, it shows the line where the error was issued inside the catch method, it does not show the line of code that divide by zero occurs
class Program
{
public static void Main()
{
try
{
DoSomething();// Line 10
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);// Line 14
}
}
public static void DoSomething()
{
try
{
int number = 20;
int division = 0;
Console.WriteLine(number / division);// Line 23
}
catch (Exception ex)
{
throw ex;// Line 27
}
}
}
If you run the program, you will see the following message on the console screen:
at Exception.Program.DoSomething() in C:\Users\Farhad\source\repos\Exception\Program.cs:line 27
at Exception.Program.Main() in C:\Users\Farhad\source\repos\Exception\Program.cs:line 10
On the console screen you will see line 27 where line 27 is inside the catch section. But if you use the throw instead of throw ex, you will see the exact location of the error on the console screen. If you change the DoSomething method as follows and run the program again, you will see the exact location of the error in StackTrace:
public static void DoSomething()
{
try
{
int number = 20;
int division = 0;
Console.WriteLine(number / division);// Line 23
}
catch (Exception)
{
throw;// Line 27
}
}
Console screen:
at Exception.Program.DoSomething() in C:\Users\Farhad\source\repos\Exception\Program.cs:line 23
at Exception.Program.Main() in C:\Users\Farhad\source\repos\Exception\Program.cs:line 10
Therefore, it is better to use throw and not to use throw ex as much as possible because it resets StackTrace and the exact location of the issued error is not known.
;)