views:

368

answers:

3

How would one display what line number caused the error

and is this even possible with the way that .net compiles its exes?

If not is there an automated way for exception.message to display the sub that crapped out?

try
{
  int x = textbox1.text;
}
catch(exception ex)
{
     messagebox.show(ex.message);
}
+3  A: 

use ex.ToString() to get the full stack trace

you must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties)

Steven A. Lowe
+1  A: 

If you use 'StackTrace' and include the .pdb files in the working directory, the stack trace should contain line numbers.

Mitch Wheat
A: 

To see the stacktrace for a given Exception, use e.StackTrace

If you need more detailed information, you can use the System.Diagnostics.StackTrace class (here is some code for you to try):

try
{
    throw new Exception();
}
catch (Exception ex)
{
    //Get a StackTrace object for the exception
    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();
}

This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file.

Gabriel McAdams