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


当前回答

如果您需要的行号不仅仅是从Exception中获得的格式化堆栈跟踪。你可以使用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文件可用时才有效。

其他回答

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

看看这个

StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);

//Get the file name
string fileName = frame.GetFileName();

//Get the method name
string methodName = frame.GetMethod().Name;

//Get the line number from the stack frame
int line = frame.GetFileLineNumber();

//Get the column number
int col = frame.GetFileColumnNumber();

我尝试使用@davy-c的解决方案,但有一个异常“系统。输入字符串的格式不正确。’”,这是由于仍然有文本超过行号,我修改了他发布的代码,并提出:

int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));

这适用于我在VS2017 c#。

在全球。resx文件中有一个名为Application_Error的事件

每当发生错误时,它就会触发,您可以很容易地获得有关错误的任何信息,并将其发送到错误跟踪电子邮件。

此外,我认为所有你需要做的是编译全局。Resx并将其dll's (2 dll)添加到您的bin文件夹,它将工作!

我添加了一个扩展到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);

    }
}