views:

1913

answers:

7

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?

A: 

Is there no C# Logging API that can take an Exception as an argument and handle everything for you, like Java's Log4J does?

I.e., use Log4NET.

JeeBee
good question :)
Epaga
it is a good question, but it is not a good answer
Steven A. Lowe
I think it points out just why Microsoft might not have provided such functionality in C# that Java did (being the older language developed in more simple times). I.e., there is a better way that is recommended.
JeeBee
+10  A: 

Try this:

Console.WriteLine(ex.ToString());

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

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment..::.StackTrace. If any of these members is nullNothingnullptra null reference (Nothing in Visual Basic), its value is not included in the returned string.

Note that in the above code the call to ToString isn't required as there's an overload that takes System.Object and calls ToString directly.

Drew Noakes
+1  A: 

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

Console.WriteLine(myException.StackTrace);

NathanE
That won't include the message or inner exception details.
Drew Noakes
+1  A: 
  catch (Exception ex)
{
    Console.WriteLine(ex.StackTrace);
}
Steve Brouillard
That won't include the message or inner exception details.
Drew Noakes
Gotcha. Thanks for the info.
Steve Brouillard
+1  A: 

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()
Jon Skeet
A: 

Also look at Log4Net... its a port of Log4J to .NET.

NathanE
+4  A: 

I would like to add: If you want to print the stack outside of an exception, you can use:

Console.WriteLine(System.Environment.StackTrace);
Ryan Cook