Is there a difference between “throw” and “throw ex”?

前端 未结 10 2528
夕颜
夕颜 2020-11-22 01:08

There are some posts that asks what the difference between those two are already.
(why do I have to even mention this...)

But my question is different in a way

10条回答
  •  不知归路
    2020-11-22 01:35

    let's understand the difference between throw and throw ex. I heard that in many .net interviews this common asked is being asked.

    Just to give an overview of these two terms, throw and throw ex are both used to understand where the exception has occurred. Throw ex rewrites the stack trace of exception irrespective where actually has been thrown.

    Let's understand with an example.

    Let's understand first Throw.

    static void Main(string[] args) {
        try {
            M1();
        } catch (Exception ex) {
            Console.WriteLine(" -----------------Stack Trace Hierarchy -----------------");
            Console.WriteLine(ex.StackTrace.ToString());
            Console.WriteLine(" ---------------- Method Name / Target Site -------------- ");
            Console.WriteLine(ex.TargetSite.ToString());
        }
        Console.ReadKey();
    }
    
    static void M1() {
        try {
            M2();
        } catch (Exception ex) {
            throw;
        };
    }
    
    static void M2() {
        throw new DivideByZeroException();
    }
    

    output of the above is below.

    shows complete hierarchy and method name where actually the exception has thrown.. it is M2 -> M2. along with line numbers

    enter image description here

    Secondly.. lets understand by throw ex. Just replace throw with throw ex in M2 method catch block. as below.

    enter image description here

    output of throw ex code is as below..

    enter image description here

    You can see the difference in the output.. throw ex just ignores all the previous hierarchy and resets stack trace with line/method where throw ex is written.

提交回复
热议问题