Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do "throw" and "throw ex" in a catch block behave the same way?

Tags:

c#

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

like image 959
cquezel Avatar asked Feb 04 '13 03:02

cquezel


People also ask

Is there a difference between throw and throw ex?

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.

Does finally run even if I throw in catch?

The finally block executes regardless of whether an exception is thrown or caught.

Can a catch block throw the exception caught by itself?

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.

What if exception is thrown in catch?

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.


1 Answers

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.

like image 65
Simon Whitehead Avatar answered Sep 20 '22 18:09

Simon Whitehead