简体   繁体   中英

Why does stack trace frame not always contain filename and line number?

When i write this code to find line which occurs error

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

It is running correctly when i throw exception like this (from Case 2 )

throw new Exception();

but any other codding errors like this (from Case 1 )

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

will throw exception i get response null from fileName and 0 from lineNo

What's is the difference about these two situation ?

Its happening because if you throw a exception like this throw new Exception(); you know the class that threw the exception because it was you who created it, and you have the code.

if the exception is thrown by a framework method like Convert.ToInt32("fdafa") you don't know the code, so, the line number and file name can not be entered. Probably, if you go up a frame ( trace.GetFrame(1) ) your class that called the method in error, you can provide her name and line number.

For example, you may notice that if you try to look at the implementation of the Convert class, you can not.

Two small changes to your code will work for both cases.


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

That is because StackTrace frame counts are different in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM