小编典典

如何获得引发异常的行号?

c#

在一个catch块中,如何获取引发异常的行号?


阅读 282

收藏
2020-05-19

共1个答案

小编典典

如果您需要的行号不仅仅是从Exception.StackTrace获得的格式化堆栈跟踪,则可以使用StackTrace类:

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

请注意,这仅在程序集有pdb文件可用时才有效。

2020-05-19