Hi
Difference between "Throw" and "Throw ex"?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Aug 27, 2012, 8:04 AM
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.
Santhosh Kumar JayaramanPosted Aug 27, 2012, 8:03 AM
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...