In general, we use the try/catch/finally statement block to catch exceptions, as we say here. What is the difference between using throw and throw ex when throwing an exception?
Assume that several methods are called as follows:
→ Call the Method1 method in the main method, Try/catch catch exception
→ Call the Method2 method in the Method1 method, Try/catch catch exception
→ Intentionally throwing exceptions in the Method2 method, Try/catch catching exceptions
Throw an exception with throw
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, throwing exceptions with throw throws out all the exceptions that occur in the Method2 method, the Method1 method, and the main method.
Throwing exceptions using throw ex
Now, in the Method1 method, throw an exception using the throw ex.
static void Method1 ()
{
Try
{
METHOD2 ();
}
catch (Exception ex)
{
Throw ex;
}
}
It can be seen that throwing an exception using throw ex will only throw out the Method1 method and the exception in the main method.
Summary: If you want to get the most complete stacktrace information, throw an exception using throw, where you know exactly which method the exception came from.
Differences in C # using throw and throw ex throw exceptions