C# equivalent to Java's Exception.printStackTrace()?
Solution 1
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.
Solution 2
I would like to add: If you want to print the stack outside of an exception, you can use:
Console.WriteLine(System.Environment.StackTrace);
Solution 3
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()
Solution 4
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx
Console.WriteLine(myException.StackTrace);
Solution 5
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Epaga
Java developer @ i-net software by day Indie iOS developer of Mindscope and In-Flight Assistant by night Husband of 1, dad of 4
Updated on January 28, 2020Comments
-
Epaga about 4 years
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? -
Drew Noakes over 15 yearsThat won't include the message or inner exception details.
-
selalerer over 4 yearsJust tried it in .Net Core 2.1 on Linux and it seems it is not true any more