在异常处理中显示行号

Cra*_*893 19 .net c# exception-handling exception line-numbers

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

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

try
{
  int x = textbox1.Text;
}
catch(Exception ex)
{
     MessageBox.Show(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*owe 47

使用ex.ToString()得到完整的堆栈跟踪.

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


Gab*_*ams 30

要查看给定Exception的堆栈跟踪,请使用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();
}
Run Code Online (Sandbox Code Playgroud)

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