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

前端 未结 10 2529
夕颜
夕颜 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:39

    To give you a different perspective on this, using throw is particularly useful if you're providing an API to a client and you want to provide verbose stack trace information for your internal library. By using throw here, I'd get the stack trace in this case of the System.IO.File library for File.Delete. If I use throw ex, then that information will not be passed to my handler.

    static void Main(string[] args) {            
       Method1();            
    }
    
    static void Method1() {
        try {
            Method2();
        } catch (Exception ex) {
            Console.WriteLine("Exception in Method1");             
        }
    }
    
    static void Method2() {
        try {
            Method3();
        } catch (Exception ex) {
            Console.WriteLine("Exception in Method2");
            Console.WriteLine(ex.TargetSite);
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine(ex.GetType().ToString());
        }
    }
    
    static void Method3() {
        Method4();
    }
    
    static void Method4() {
        try {
            System.IO.File.Delete("");
        } catch (Exception ex) {
            // Displays entire stack trace into the .NET 
            // or custom library to Method2() where exception handled
            // If you want to be able to get the most verbose stack trace
            // into the internals of the library you're calling
            throw;                
            // throw ex;
            // Display the stack trace from Method4() to Method2() where exception handled
        }
    }
    

提交回复
热议问题