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
Unlike throw ex, throw provides all stack information. The main difference between throw and throw ex in C# is that throw provides information about from where the exception was thrown and also about the actual exception while throw ex provides information only about from where the exception was thrown.
The finally block executes regardless of whether an exception is thrown or caught.
Q29)Can a catch block throw the exception caught by itself? Ans) Yes. This is called rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again.
Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
throw
will 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With