C # equivalent to Java Exception.printStackTrace ()?

Is there an equivalent C # method for Java Exception.printStackTrace() or do I need to write something while working through InnerExceptions?

+55
stack-trace c # exception
Dec 02 '08 at 13:45
source share
7 answers

Try the following:

 Console.WriteLine(ex.ToString()); 

From http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx :

The default implementation for ToString, by default, gets the class name that throws the current exception, the message, the result of the ToString call in the internal exception, and the result of the .StackTrace environment call. If any of these elements is NULL, its value is not included in the returned string.

Note that in the above code, a ToString call is not required, as there is an overload that takes System.Object and calls ToString directly.

+85
Dec 02 '08 at 13:48
source share

I would like to add: if you want to print the stack with no exception, you can use:

 Console.WriteLine(System.Environment.StackTrace); 
+65
Dec 04 '08 at 8:32
source share

As Drew says, simply by throwing an exception, the line does this. For example, 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 conclusion:

 System.Exception: Outer ---> System.Exception: Inner at Test.ThrowException2() at Test.ThrowException() --- End of inner exception stack trace --- at Test.ThrowException() at Test.Main() 
+8
Dec 02 '08 at 13:52
source share
+2
Dec 02 '08 at 13:49
source share
  catch (Exception ex) { Console.WriteLine(ex.StackTrace); } 
+1
Dec 02 '08 at 13:50
source share

Is there a C # Logging API that can take an exception as an argument and handle everything for you, like Java Log4J?

Ie, use Log4NET.

0
Dec 02 '08 at 13:47
source share

Also look at Log4Net ... its Log4J port on .NET.

-one
Dec 02 '08 at 13:52
source share



All Articles