Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# equivalent to Python's traceback library

In this post, python has traceback library to get some detailed error information (line number, file name ...).

Does C# have similar functions to know what file/line number that generates the exception?

ADDED

I came up with the following code based on the answers.

using System;

// https://stackoverflow.com/questions/4474259/c-exception-handling-with-a-string-given-to-a-constructor

class WeekdayException : Exception {
    public WeekdayException(String wday) : base("Illegal weekday: " + wday) {}
}

class TryCatchFinally 
{
    public static void Main() 
    {
        try
        {
            throw new WeekdayException("thrown by try");
        }
        catch(WeekdayException weekdayException) {
            Console.WriteLine(weekdayException.Message);
            Console.WriteLine(weekdayException.StackTrace);
        }
    }
}

And it gives me this message:

Illegal weekday: thrown by try
  at TryCatchFinally.Main () [0x00000] in <filename unknown>:0 
like image 335
prosseek Avatar asked Jan 01 '26 01:01

prosseek


1 Answers

When you catch an exception you can view its stack trace, which should give similar results:

catch(Exception e)
{
    Console.WriteLine(e.StackTrace);
}

If debug data can be loaded (if the .pdb file is in the same directory as the executable/you build in debug mode) this will include file names line numbers. If not it will only include method names.

like image 147
Phil Lamb Avatar answered Jan 02 '26 13:01

Phil Lamb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!