开发者

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

开发者 https://www.devze.com 2022-12-28 03:37 出处:网络
This question already has answers here: Closed 10 years ago. 开发者_如何学Python Possible Duplicate:
This question already has answers here: Closed 10 years ago. 开发者_如何学Python

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.


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)


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.


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.


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.


You can find it in the stack trace (Exception.StackTrace property), on the last line, but only when your code has been compiled with debugging information included. Otherwise the line number will be unknown.

0

精彩评论

暂无评论...
验证码 换一张
取 消