What is the difference between ex.StackTrace vs ex.toString() for exceptions in C#/.NET? Does toString() include also the message and the StackTrace?
CodePudding user response:
From the Exception.ToString documentation:
The default implementation of
ToStringobtains the name of the class that threw the current exception, the message, the result of callingToStringon the inner exception, and the result of callingEnvironment.StackTrace. If any of these members isnull, its value is not included in the returned string.If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not
null.
CodePudding user response:
Exception.StackTrace will give you the value of the StackTrace property of your exception.
Exception.ToString() will give you a verbose exception description, including the non-null properties.
For an example, if we just create a simple app to throw a random exception, we can see the results.
Exception.StackTrace
at CS_Console_NetFramework.Program.Main(String[] args) in H:\Viusal Studio Repos\!Test Projects\Misc Consoles\CS_Console_NetFramework\CS_Console_NetFramework\Program.cs:line 12
Exception.ToString()
System.InvalidCastException: Specified cast is not valid. at CS_Console_NetFramework.Program.Main(String[] args) in H:\Viusal Studio Repos\!Test Projects\Misc Consoles\CS_Console_NetFramework\CS_Console_NetFramework\Program.cs:line 12
As you can see, we got a little more detail from Exception.ToString().
