开发者

C# equivalent to Python's traceback library

开发者 https://www.devze.com 2023-01-31 08:12 出处:网络
In this post, python has traceback library to get some detailed error information (line number, file name ...).

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 &开发者_运维问答lt;filename unknown>:0 


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.


When an exception gets thrown, check out the stack trace - it will give you the same results.


All classes that inherit from Exception have a StackTrace property. It's not quite the same as the Python traceback library because of the nature of how C#/.NET is run (like it won't have an equivalent to tb_lineno). All it is is the string representation of the stack trace.

0

精彩评论

暂无评论...
验证码 换一张
取 消