C# equivalent to Java's Exception.printStackTrace()?

后端 未结 8 1510
刺人心
刺人心 2021-01-31 13:13

Is there a C# equivalent method to Java\'s Exception.printStackTrace() or do I have to write something myself, working my way through the InnerExceptions?

8条回答
  •  半阙折子戏
    2021-01-31 13:58

    As Drew says, just converting the exception a string does this. For instance, this program:

    using System;
    
    class Test
    {
        static void Main()
        {
            try
            {
                ThrowException();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    
        static void ThrowException()
        {
    
            try
            {
                ThrowException2();
            }
            catch (Exception e)
            {
                throw new Exception("Outer", e);
            }
        }
    
        static void ThrowException2()
        {
            throw new Exception("Inner");
        }
    }
    

    Produces this output:

    System.Exception: Outer ---> System.Exception: Inner
       at Test.ThrowException2()
       at Test.ThrowException()
       --- End of inner exception stack trace ---
       at Test.ThrowException()
       at Test.Main()
    

提交回复
热议问题