在异常处理中显示行号
如何显示导致错误的行号?这是否可以通过 .NET 编译其 .exe 的方式实现?
如果没有, Exception.Message 是否有一种自动方式来显示崩溃的子程序?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
How would one display what line number caused the error and is this even possible with the way that .NET compiles its .exes?
If not is there an automated way for Exception.Message to display the sub that crapped out?
try
{
int x = textbox1.Text;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 ex.ToString() 获取完整的堆栈跟踪。
即使在发布模式下,您也必须使用调试符号(.pdb 文件)进行编译,才能获取行号(这是项目构建属性中的一个选项)。
Use
ex.ToString()
to get the full stack trace.You must compile with debugging symbols (.pdb files), even in release mode, to get the line numbers (this is an option in the project build properties).
要查看给定异常的堆栈跟踪,请使用 e.StackTrace
如果您需要更详细的信息,可以使用系统。 Diagnostics.StackTrace 类(这里有一些代码供您尝试):
只有当程序集有可用的 pdb 文件时,这才有效。 查看项目属性 - 构建选项卡 - 高级 - 调试信息选择以确保存在 pdb 文件。
To see the stacktrace for a given Exception, use e.StackTrace
If you need more detailed information, you can use the System.Diagnostics.StackTrace class (here is some code for you to try):
This will only work if there is a pdb file available for the assembly. See the project properties - build tab - Advanced - Debug Info selection to make sure there is a pdb file.
如果您使用 'StackTrace' 并包含 . pdb 文件位于工作目录中,堆栈跟踪应包含行号。
If you use 'StackTrace' and include the .pdb files in the working directory, the stack trace should contain line numbers.
这样你就可以从异常中获取行号
this way you can Get Line number from Exception
如果生成异常的库是使用调试符号编译的,则行号将包含在堆栈跟踪中。 这可以是单独的文件 (*.pdb) 或嵌入到库中。
对于 .NET Core、.NET 5 及更高版本,要在发布版本中具有完整的异常行号,请按如下方式配置项目:
上述配置将直接在构建文件中包含调试符号,这些文件可以作为 nuget 发布。
上述方法的替代方法是将调试包与主 nuget 包一起恢复,目前尚不支持: https://github.com/NuGet/Home/issues/9667
现在获取异常行号:
Line numbers will be included in the stack trace if the library which generated the exception is compiled with debug symbols. This can be a separate file (*.pdb) or embedded in the library.
For .NET Core, .NET 5 and later, to have full exception line numbers in release builds, configure the project as follows:
The above configuration will include debug symbols directly with the built files, which can be published as nugets.
An alternative to the above is to restore debug packages together with the main nuget packages, which is currently not yet supported: https://github.com/NuGet/Home/issues/9667
Now get the exception line numbers:
是否可以简单地从 ex 公开的 StackTrace 中获取顶部框架?
Is it possible to simply get the top frame from the StackTrace exposed by ex?