Alexander Abramovich
Alexander Abramovich

Reputation: 11458

pretty printing exceptions in C#

Is there any API that allows to prints all the exception-related info (stack trace, inner etc...)? Just like when the exception is thrown - all the data is printed to the standard output - is there any dedicated method that does it all?

thanks

Upvotes: 32

Views: 47705

Answers (4)

Sergio Perez
Sergio Perez

Reputation: 641

For printing exceptions in C#, you can use Debug.WriteLine():

    try
    {
        reader = cmd.ExecuteReader();
    }
    catch (Exception ex)
    {
        Debug.WriteLine("<<< catch : "+ ex.ToString());
    }

Also, you can use this for other exceptions, for example with MySqlException:

   try
    {
        reader = cmd.ExecuteReader();
    }
    catch (MySqlException ex)
    {
        Debug.WriteLine("<<< catch : "+ ex.ToString());            
    }

But, if you need printing a Exception's Message, you have to use Message:

    try
    {
        reader = cmd.ExecuteReader();
    }
    catch (MySqlException ex)
    {
        Debug.WriteLine("<<< catch : "+ ex.Message);            
    }

Upvotes: 1

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 121067

the ToString method of Exception does exactly that.

Upvotes: 7

to StackOverflow
to StackOverflow

Reputation: 124804

Exception.ToString() ?

Upvotes: 2

jgauffin
jgauffin

Reputation: 101192

Console.WriteLine(exception.ToString());

Upvotes: 58

Related Questions