I read that when in a catch block, I can rethrow the current exception using “throw;” or “throw ex;”.
From: http://msdn.microsoft.com/en-us/library/ms182363%28VS.80%29.aspx
“To keep the original stack trace information with the exception, use the throw statement without specifying the exception.”
But when I try this with
try{
try{
try{
throw new Exception("test"); // 13
}catch (Exception ex1){
Console.WriteLine(ex1.ToString());
throw; // 16
}
}catch (Exception ex2){
Console.WriteLine(ex2.ToString()); // expected same stack trace
throw ex2; // 20
}
}catch (Exception ex3){
Console.WriteLine(ex3.ToString());
}
I get three different stacks. I was expecting the first and second trace to be the same. What am I doing wrong? (or understanding wrong?)
System.Exception: test
at ConsoleApplication1.Program.Main(String[] args) in c:\Program.cs:line 13
System.Exception: test
at ConsoleApplication1.Program.Main(String[] args) in c:\Program.cs:line 16
System.Exception: test
at ConsoleApplication1.Program.Main(String[] args) in c:\Program.cs:line 20
throwwill only preserve the stack frame if you don’t throw it from within the current one. You’re doing just that by doing all of this in one method.See this answer: https://stackoverflow.com/a/5154318/1517578
PS: +1 for asking a question that was actually a valid question.