There are some posts that asks what the difference between those two are already.
(why do I have to even mention this...)
But my question is different in a way
let's understand the difference between throw and throw ex. I heard that in many .net interviews this common asked is being asked.
Just to give an overview of these two terms, throw and throw ex are both used to understand where the exception has occurred. Throw ex rewrites the stack trace of exception irrespective where actually has been thrown.
Let's understand with an example.
Let's understand first Throw.
static void Main(string[] args) {
try {
M1();
} catch (Exception ex) {
Console.WriteLine(" -----------------Stack Trace Hierarchy -----------------");
Console.WriteLine(ex.StackTrace.ToString());
Console.WriteLine(" ---------------- Method Name / Target Site -------------- ");
Console.WriteLine(ex.TargetSite.ToString());
}
Console.ReadKey();
}
static void M1() {
try {
M2();
} catch (Exception ex) {
throw;
};
}
static void M2() {
throw new DivideByZeroException();
}
output of the above is below.
shows complete hierarchy and method name where actually the exception has thrown.. it is M2 -> M2. along with line numbers
Secondly.. lets understand by throw ex. Just replace throw with throw ex in M2 method catch block. as below.
output of throw ex code is as below..
You can see the difference in the output.. throw ex just ignores all the previous hierarchy and resets stack trace with line/method where throw ex is written.