在异常处理中显示行号

时间:2009-03-27 02:44:13

标签: c# .net exception exception-handling line-numbers

如何显示导致错误的行号,这是否可能与.NET编译其.exes的方式有关?

如果没有Exception.Message的自动方式来显示被淘汰的子?

try
{
  int x = textbox1.Text;
}
catch(Exception ex)
{
     MessageBox.Show(ex.Message);
}

6 个答案:

答案 0 :(得分:46)

使用ex.ToString()获取完整的堆栈跟踪。

即使在发布模式下,您也必须使用调试符号(.pdb文件)进行编译,以获取行号(这是项目构建属性中的一个选项)。

答案 1 :(得分:29)

要查看给定异常的堆栈跟踪,请使用e.StackTrace

如果您需要更详细的信息,可以使用System.Diagnostics.StackTrace课程(这里有一些代码供您试用):

try
{
    throw new Exception();
}
catch (Exception ex)
{
    //Get a StackTrace object for the exception
    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();
}

仅当有可用于程序集的pdb文件时,此操作才有效。请参阅项目属性 - 构建选项卡 - 高级 - 调试信息选择以确保存在pdb文件。

答案 2 :(得分:4)

如果使用'StackTrace'并在工作目录中包含.pdb文件,则堆栈跟踪应包含行号。

答案 3 :(得分:1)

string lineNumber=e.StackTrace.Substring(e.StackTrace.Length - 7, 7);

答案 4 :(得分:0)

这样,您可以从异常中获取行号

public int GetLineNumber(Exception ex)
{

    const string lineSearch = ":line ";
    var index = ex.StackTrace.LastIndexOf(lineSearch);
    int ln=0;
    if (index != -1)
    {


        var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
        string lnum = System.Text.RegularExpressions.Regex.Match(lineNumberText, @"\d+").Value;
        int.TryParse(lnum,out ln);

    }
    return ln;
}

答案 5 :(得分:0)

如果使用调试符号编译生成异常的库,行号将包含在堆栈跟踪中。这可以是单独的文件 (*.pdb) 或嵌入到库中。

对于 .NET Core、.NET 5 及更高版本,要在发布版本中具有完整的异常行号,请按如下方式配置项目:

<PropertyGroup>    
  <DebugSymbols>true</DebugSymbols>
  <DebugType>embedded</DebugType>

    <!-- Only enable the following if the line numbers mismatch -->
    <!--<Optimize>false</Optimize>-->
    
    <!--
      Additional properties which may impact how printed line numbers match the source code line numbers are listed here:
      https://docs.microsoft.com/en-us/dotnet/core/run-time-config/compilation
    -->
</PropertyGroup>

上述配置将直接在构建文件中包含调试符号,可以将其发布为 nuget。

上述替代方法是将调试包与主要 nuget 包一起恢复,目前尚不支持:https://github.com/NuGet/Home/issues/9667

现在获取异常行号:

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();
}