C # - получить номер строки, выдавшей исключение - PullRequest
173 голосов
/ 25 июля 2010

В блоке catch как я могу получить номер строки, которая вызвала исключение?

Ответы [ 11 ]

246 голосов
/ 25 июля 2010

Если вам нужен номер строки не только для отформатированной трассировки стека, полученной из Exception.StackTrace, вы можете использовать класс 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 для сборки.

55 голосов
/ 25 июля 2010

Простой способ, используйте функцию Exception.ToString(), она вернет строку после описания исключения.

Вы также можете проверить базу данных отладки программы, так как она содержит отладочную информацию / журналы обо всем приложении.

25 голосов
/ 13 февраля 2015

Если у вас нет файла .PBO:

C #

public int GetLineNumber(Exception ex)
{
    var lineNumber = 0;
    const string lineSearch = ":line ";
    var index = ex.StackTrace.LastIndexOf(lineSearch);
    if (index != -1)
    {
        var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
        if (int.TryParse(lineNumberText, out lineNumber))
        {
        }
    }
    return lineNumber;
}

Vb.net

Public Function GetLineNumber(ByVal ex As Exception)
    Dim lineNumber As Int32 = 0
    Const lineSearch As String = ":line "
    Dim index = ex.StackTrace.LastIndexOf(lineSearch)
    If index <> -1 Then
        Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
        If Int32.TryParse(lineNumberText, lineNumber) Then
        End If
    End If
    Return lineNumber
End Function

Или как расширение класса Exception

public static class MyExtensions
{
    public static int LineNumber(this Exception ex)
    {
        var lineNumber = 0;
        const string lineSearch = ":line ";
        var index = ex.StackTrace.LastIndexOf(lineSearch);
        if (index != -1)
        {
            var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
            if (int.TryParse(lineNumberText, out lineNumber))
            {
            }
        }
        return lineNumber;
    }
}   
17 голосов
/ 25 июля 2010

Вы можете включить .PDB файлы символов, связанные со сборкой, которые содержат информацию метаданных, и когда генерируется исключение, оно будет содержать полную информацию в трассировке стека о том, где это исключение возникло. Он будет содержать номера строк каждого метода в стеке.

7 голосов
/ 18 июля 2014

Работает:

var LineNumber = new StackTrace(ex, True).GetFrame(0).GetFileLineNumber();
2 голосов
/ 07 сентября 2016

Отметьте это

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();
1 голос
/ 25 октября 2018

Я пытался использовать решение By @ davy-c, но было исключение «System.FormatException:« Входная строка была не в правильном формате. » код он отправил и придумал:

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 #.

1 голос
/ 14 октября 2015

Обновление до ответа

    // 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(st.FrameCount-1);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
0 голосов
/ 17 декабря 2018

Метод расширения

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);
}
0 голосов
/ 12 января 2014

Это работает для меня:

try
{
  //your code;
}
catch(Exception ex)
{
  MessageBox.Show(ex.StackTrace + " ---This is your line number, bro' :)", ex.Message);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...