异常处理 - 显示行号发生错误? [英] Exception handling -- display line number where error occurred?

查看:183
本文介绍了异常处理 - 显示行号发生错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
异常



有人可以显示行数处理


请告诉我怎么去哪里出现了错误代码的行数,并将其显示在控制台?



如文件名或方法名的其他资料会很派上用场了。


解决方案

您可以通过使用代码周围的一个try / catch,可以抛出,然后使用打印整个堆栈跟踪< A HREF =htt​​p://msdn.microsoft.com/en-us/library/swx4tc5e.aspx相对=nofollow> Console.WriteLine 显示异常对象:

 
{
新计划()的run()。
}
赶上(例外的例外)//不想搭上了更具体的execption。
{
Console.WriteLine(例外);
}



输出:

  System.IndexOutOfRangeException:索引是该数组的范围之外。 
在Program.Run()在C:\Console Application1\Program.cs:行37
在Program.Main(字串[] args)在C:\Console Application1\Program。 CS:线45

的第一行示出了异常,并且该消息的类型。第二行显示了异常被抛出文件,函数和行号。您还可以看到以下行调用堆栈上其他呼叫的位置。



您还可以获取文件和行号为捕获的异常。您可以通过添加为 AppDomain.UncaughtException 事件对当前的AppDomain:

 静态无效的主要(字串[] args)
{
AppDomain.CurrentDomain.UnhandledException + = CurrentDomain_UnhandledException;
新计划()的run()。
}

静态无效CurrentDomain_UnhandledException(对象发件人,UnhandledExceptionEventArgs E)
{
Console.WriteLine(e.ExceptionObject);
}

这显示了类似的输出上面。


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.

解决方案

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.

这篇关于异常处理 - 显示行号发生错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆