Hi
Difference between "Throw" and "Throw ex"?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Santhosh Kumar JayaramanRank #563 · 4.3K reputationPosted Aug 27, 2012, 4:03 AM EDT
I find a good sample code in the below link.,
http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex
static void Main(string[] args) {
try {
ThrowException1(); // line 19
} catch (Exception x) {
Console.WriteLine("Exception 1:");
Console.WriteLine(x.StackTrace);
}
try {
ThrowException2(); // line 25
} catch (Exception x) {
Console.WriteLine("Exception 2:");
Console.WriteLine(x.StackTrace);
}
}
private static void ThrowException1() {
try {
DivByZero(); // line 34
} catch {
throw; // line 36
}
}
private static void ThrowException2() {
try {
DivByZero(); // line 41
} catch (Exception ex) {
throw ex; // line 43
}
}
private static void DivByZero() {
int x = 0;
int y = 1 / x; // line 49
}
and here is the output:
Exception 1:
at UnitTester.Program.DivByZero() in
at UnitTester.Program.ThrowException1() in
at UnitTester.Program.TestExceptions() in
Exception 2:
at UnitTester.Program.ThrowException2() in
at UnitTester.Program.TestExceptions() in
You can see that in Exception 1, the stack trace goes back to the DivByZero() method, whereas in Exception 2 it does not.
Take note, though, that the line number shown in ThrowException1() and ThrowException2() is the line number of the throw statement, not the line number of the call to DivByZero(), which probably makes sense now that I think about it a bit...
Jignesh TrivediRank #16 · 50.3K reputationPosted Aug 27, 2012, 4:04 AM EDT
Hi,
In Throw Ex, the original stack trace info gets overwritten. So you loose original exceptions's stack trace as only the last point from which the exception was thrown is available.
Throw, on the other hand retains the stack trace with the original point of exception available.
Please refer...
http://geekswithblogs.net/sdorman/archive/2007/08/20/Difference-between-quotthrowquot-and-quotthrow-exquot-in-.NET.aspx
hope this will help you.