Show line number in exception handling

戏子无情 提交于 2019-11-26 13:58:25

问题


How would one display what line number caused the error and is this even possible with the way that .NET compiles its .exes?

If not is there an automated way for Exception.Message to display the sub that crapped out?

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

回答1:


Use ex.ToString() to get the full stack trace.

You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties).




回答2:


To see the stacktrace for a given Exception, use e.StackTrace

If you need more detailed information, you can use the System.Diagnostics.StackTrace class (here is some code for you to try):

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

This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file.




回答3:


If you use 'StackTrace' and include the .pdb files in the working directory, the stack trace should contain line numbers.




回答4:


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



回答5:


this way you can Get Line number from Exception

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


来源:https://stackoverflow.com/questions/688336/show-line-number-in-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!