C#相当于Python的追溯库 [英] C# equivalent to Python's traceback library
问题描述
在这篇文章,python有追溯库,以获取一些详细的错误信息(行号,文件名...)。
In this post, python has traceback library to get some detailed error information (line number, file name ...).
C#有类似的功能来知道什么文件/行号产生异常?
Does C# have similar functions to know what file/line number that generates the exception?
我想出了以下代码答案。
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);
}
}
}
它给我这个消息:
Illegal weekday: thrown by try
at TryCatchFinally.Main () [0x00000] in <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);
}
如果可以加载调试数据(如果.pdb文件是相同的目录作为可执行文件/您在调试模式下构建),这将包括文件名行行号。如果不是,它只会包含方法名称。
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.
这篇关于C#相当于Python的追溯库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!