在捕获块中,如何获得抛出异常的行号?


当前回答

扩展方法

static class ExceptionHelpers
{
    public static int LineNumber(this Exception ex)
    {
        int n;
        int i = ex.StackTrace.LastIndexOf(" ");
        if (i > -1)
        {
            string s = ex.StackTrace.Substring(i + 1);
            if (int.TryParse(s, out n))
                return n;
        }
        return -1;
    }
}

使用

try
{
    throw new Exception("A new error happened");
}
catch (Exception ex)
{
    //If error in exception LineNumber() will be -1
    System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
}

其他回答

为我工作:

var st = new StackTrace(e, true);

// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();

我添加了一个扩展到Exception,它返回行,列,方法,文件名和消息:

public static class Extensions
{
    public static string ExceptionInfo(this Exception exception)
    {

        StackFrame stackFrame = (new StackTrace(exception, true)).GetFrame(0);
        return string.Format("At line {0} column {1} in {2}: {3} {4}{3}{5}  ",
           stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber(),
           stackFrame.GetMethod(), Environment.NewLine, stackFrame.GetFileName(),
           exception.Message);

    }
}

简单的方法,使用exception . tostring()函数,它将返回异常描述之后的行。

您还可以检查程序调试数据库,因为它包含关于整个应用程序的调试信息/日志。

您可以包含与程序集关联的. pdb符号文件,其中包含元数据信息,当抛出异常时,它将在异常起源的堆栈跟踪中包含完整的信息。它将包含堆栈中每个方法的行号。

如果你的堆栈跟踪大于1,它应该是:

var st = new StackTrace(es, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount - 1);

//从栈帧中获取行号 var line = frame.GetFileLineNumber();