예외가 발생한 줄 번호는 어떻게 알 수 있습니까? catch블록, 어떻게 예외를 던져

A의 catch블록, 어떻게 예외를 던져 줄 번호를받을 수 있나요?



답변

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 파일이있는 경우에만 작동합니다.


답변

간단한 방법으로 Exception.ToString()함수를 사용 하면 예외 설명 후에 줄을 반환합니다.

전체 응용 프로그램에 대한 디버그 정보 / 로그가 포함 된 프로그램 디버그 데이터베이스를 확인할 수도 있습니다.


답변

.PBO파일 이없는 경우 :

씨#

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

답변

당신은 포함 할 수 .PDB메타 데이터 정보를 포함하고 예외가 발생 될 때이 예외가 발생한 위치의 스택 트레이스 전체 정보가 포함됩니다 어셈블리에 관련된 기호 파일을. 스택에있는 각 메소드의 행 번호를 포함합니다.


답변

효과가있다:

var LineNumber = new StackTrace(ex, True).GetFrame(0).GetFileLineNumber();

답변

이것 좀 봐

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

답변

답변으로 업데이트

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