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?

- 300,895
- 165
- 679
- 742

- 38,231
- 58
- 157
- 245
8 Answers
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 null, 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.

- 300,895
- 165
- 679
- 742
-
1Just tried it in .Net Core 2.1 on Linux and it seems it is not true any more – selalerer Nov 14 '19 at 12:33
I would like to add: If you want to print the stack outside of an exception, you can use:
Console.WriteLine(System.Environment.StackTrace);

- 9,275
- 5
- 38
- 37
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()

- 1,421,763
- 867
- 9,128
- 9,194
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx
Console.WriteLine(myException.StackTrace);

- 7,739
- 3
- 27
- 32
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.

- 17,476
- 5
- 50
- 60
-
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 Dec 02 '08 at 13:58
Since @ryan-cook answer didn't work for me, if you want to print the stack trace without having an exception, you can use:
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
Console.WriteLine(stackTrace)
Unfortunately, this can't be done in a PCL or in a .NETStandard Library

- 1,678
- 20
- 32