Exception handling -- Display line number where error occurred?

c#, exception, line, show

Solution

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.

Problem

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.

Original source

Related problems