C# equivalent to Python's traceback library

半腔热情 提交于 2019-12-12 21:27:12

问题


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 

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4474326/c-sharp-equivalent-to-pythons-traceback-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!