在应用程序中,应始终尽最大努力确保代码经过充分测试,并且以正确处理格式错误的输入或操作的方式编写。
我们只是人类,错误会悄悄出现,在改善用户体验的最后努力中,而不是毫不客气地崩溃到桌面,通常会捕获未处理的异常,向用户抛出消息并记录一些故障信息.
通常 PDB 不会与完成的程序一起分发,因此系统跟踪不会包含行号,这可能会导致很难找到引发错误的违规行。
采用以下示例程序(为简单起见,.net 控制台应用程序)
using System;
namespace ExceptionTest
{
class Program
{
static void Main(string[] args)
{
// Just in case we forget to catch something properly.
System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
Console.WriteLine(DoStuff(10));
Console.ReadKey();
}
static int DoStuff(int parameter)
{
int[] data = { 1, 2, 3, 4, 5, 6 };
int value = data[parameter]; // Improperly checked code
return value;
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
Environment.Exit(1);
}
}
}
如果在没有 .pdb 文件的情况下运行,它将尽职地捕获错误并报告它。
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at ExceptionTest.Program.DoStuff(Int32 parameter)
at ExceptionTest.Program.Main(String[] args)
Press Enter to continue
是否有任何方法可以将发生故障的点包含在用户代码中,或者这根本不存在于可执行文件中(显然包含一些符号信息,因为我们可以看到 DoStuff 函数名称。
例如,除了堆栈跟踪之外,还有什么方法可以记录 int value = data[parameter];
。
最佳答案
您在没有 PDB 的调用堆栈中看到的内容是可用的,因为您的 C# 代码是作为中间语言 (IL) 提供的。
这样想:您可以通过反射执行的所有操作(例如,请求类和请求类的方法)也可以在 IL 代码中使用,因此可以成为堆栈跟踪的一部分。
但是,IL 代码仍然在发布版本中进行了优化,例如可以删除未使用的变量。
Is there any way to include the point
没有。该信息位于 PDB 中。我们的想法是,您甚至可以为发布版本构建 PDB,并且 store them in a symbol server至少对于您交付给客户的版本而言是如此。
我也不只是捕获异常并向用户显示信息或将其保存在日志文件中。相反,create a crash dump您可以使用为此目的而存储的 PDB 在 PC 上分析该文件 (.DMP)。
关于c# - 没有 pdb 文件的堆栈跟踪中更具体的异常位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68402737/