The difference between throwing an exception using throw and throw ex in C,
Generally, we use try/catch/finally statement blocks to catch exceptions, as we mentioned here. What is the difference between throw and throw ex when an exception is thrown?
Assume that several methods are called as follows:
→ Call the Method1 method in the Main method. try/catch exceptions.
→ Call the Method2 method in the Method1 method. try/catch exceptions.
→ Intentionally throw an exception in the Method2 method. try/catch the exception.
Throw an exception
static void Main(string[] args)
{
try
{
Method1();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
Console.ReadKey();
}
static void Method1()
{
try
{
Method2();
}
catch (Exception ex)
{
throw;
}
}
static void Method2()
{
try
{
Throw new Exception ("Exception from method 2 ");
}
catch (Exception ex)
{
throw;
}
}
As you can see, throw an exception and throw all the exceptions in the Method2 method, Method1 method, and Main method.
Throw an exception using throw ex
In the Method1 method, throw ex is used to throw an exception.
static void Method1()
{
try
{
Method2();
}
catch (Exception ex)
{
throw ex;
}
}
It can be seen that throwing an exception using throw ex only throws the exception in the Method1 method and Main method.
Conclusion: If you want to obtain the most complete StackTrace information, throw an exception to know which method the exception actually came from.