Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling -- Display line number where error occurred? [duplicate]

Possible Duplicate:
Show line number in exception handling

Can someone please tell me how to get the line number of the code where the error occurred and display it to the console?

Other information like the file name or method name would be very handy.

like image 338
CSharp Noob Avatar asked Apr 27 '10 17:04

CSharp Noob


4 Answers

If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.

using System;
using System.Diagnostics;
namespace ConsoleApplication1
{
  class Program
  {    
    static void Main(string[] args)
    {      
      try
      {
        TestFunction();
      }
      catch (Exception ex)
      {
        StackTrace st = new StackTrace(ex, true);
        StackFrame[] frames = st.GetFrames();

        // Iterate over the frames extracting the information you need
        foreach (StackFrame frame in frames)
        {
          Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
        }
      }

      Console.ReadKey();
    }

    static void TestFunction()
    {      
      throw new InvalidOperationException();
    }
  }
}

The output from the above code looks like this

D:\Source\NGTests\ConsoleApplication1\Program.cs:TestFunction(30,7)
D:\Source\NGTests\ConsoleApplication1\Program.cs:Main(11,9)
like image 52
Chris Taylor Avatar answered Nov 13 '22 12:11

Chris Taylor


You can print the entire stack trace by using a try/catch around the code that can throw and then using Console.WriteLine to show the exception object:

try
{
    new Program().Run();
}
catch (Exception exception)   // Prefer to catch a more specific execption.
{
    Console.WriteLine(exception);
}

Output:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Program.Run() in C:\Console Application1\Program.cs:line 37
   at Program.Main(String[] args) in C:\Console Application1\Program.cs:line 45

The first line shows the type of the exception and the message. The second line shows the file, function and line number where the exception was thrown. You can also see the locations of other calls on the call stack in the following lines.

You can also get file and line numbers for uncaught exceptions. You can do this by adding a handler for the AppDomain.UncaughtException event on the current AppDomain:

static void Main(string[] args)
{
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    new Program().Run();
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Console.WriteLine(e.ExceptionObject);
}

This shows a similar output to above.

like image 41
Mark Byers Avatar answered Nov 13 '22 12:11

Mark Byers


Console.WriteLine(exception.StackTrace);

Make sure your application is in Debug mode or include the debug symbols (the .mdb file) in order for line numbers to appear.

like image 5
Glennular Avatar answered Nov 13 '22 12:11

Glennular


You can get the stack trace by accessing Exception.StackTrace which is a string so you can print it to the console by using the Write or WriteLine methods.

like image 2
kemiller2002 Avatar answered Nov 13 '22 14:11

kemiller2002