为什么堆栈跟踪帧不总是包含文件名和行号?

问题描述 投票:0回答:2

当我写这个代码来找到发生错误的行

// Case 1
try
{   
    var error= Convert.ToInt32("fdafa"); 
}
catch(Exception ex)
{
    StackTrace trace = new StackTrace(ex, true);
    string fileName = trace.GetFrame(0).GetFileName();
    int lineNo = trace.GetFrame(0).GetFileLineNumber(); 
}

// Case 2
try
{   
    throw new Exception();
}
catch(Exception ex)
{
    StackTrace trace = new StackTrace(ex, true);
    string fileName = trace.GetFrame(0).GetFileName();
    int lineNo = trace.GetFrame(0).GetFileLineNumber(); 
}      

当我抛出这样的异常时(从Case 2)它正常运行

throw new Exception();

但是这样的任何其他编码错误(来自Case 1

var error= Convert.ToInt32("fdafa"); 

将抛出异常我从fileName得到响应null,从lineNo得到0

这两种情况的区别是什么?

c# stack-trace
2个回答
3
投票

它的发生是因为如果你抛出一个像这个throw new Exception();的异常,你知道抛出异常的类,因为是你创建了它,并且你有代码。

如果像Convert.ToInt32("fdafa")这样的框架方法抛出异常,则您不知道代码,因此,无法输入行号和文件名。也许,如果你上一个框架(trace.GetFrame(1))你的类错误地调用了这个方法,你可以提供她的名字和行号。

例如,您可能会注意到,如果您尝试查看Convert类的实现,则不能。


0
投票

对您的代码进行两处小的更改将适用于这两种情况。


    try
    {   
        var error= Convert.ToInt32("fdafa"); 
    }
    catch(Exception ex)
    {
        StackTrace trace = new StackTrace(ex, true);
        string fileName = trace.GetFrame(trace.FrameCount - 1).GetFileName();
        int lineNo = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber(); 
    }

这是因为StackTrace帧数在每种情况下都不同。

© www.soinside.com 2019 - 2024. All rights reserved.