Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Source file,method and line in exception

Tags:

c#

.net

exception

I am trying to get details from an exception occurred in my c# (4.0) asp.net web application. I have .pdb file in bin folder. The following code is not working as expected -

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        //throwing Exception
        using (SqlConnection connection=new SqlConnection(""))
        {
            connection.Open();
        }
    }
    catch (Exception exception)
    {
        //Get a StackTrace object for the exception
        StackTrace st = new StackTrace(exception, true);

        //Get the first stack frame
        StackFrame frame = st.GetFrame(0); //returns {PermissionDemand at offset 5316022 in file:line:column <filename unknown>:0:0}

        //Get the file name
        string fileName = frame.GetFileName(); //returns null

        //Get the method name
        string methodName = frame.GetMethod().Name; //returns PermissionDemand

        //Get the line number from the stack frame
        int line = frame.GetFileLineNumber(); //returns 0

        //Get the column number
        int col = frame.GetFileColumnNumber(); //returns 0              
    }
}

What is wrong here?

update: "StackFrame frame = st.GetFrame(st.FrameCount - 1); " solved this issue.

like image 296
s.k.paul Avatar asked Oct 09 '13 05:10

s.k.paul


People also ask

How can I get the line number which threw exception?

Simple way, use the Exception. ToString() function, it will return the line after the exception description. You can also check the program debug database as it contains debug info/logs about the whole application.

Which method displays the line number in code where exception happened?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred.

What happens when exception is thrown?

When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.


1 Answers

//Remove this line
StackFrame frame = st.GetFrame(0);

//Add this line
StackFrame frame = st.GetFrame(st.FrameCount - 1);
like image 68
s.k.paul Avatar answered Oct 06 '22 04:10

s.k.paul