如何获取引发异常的行号? [英] How can I get the line number which threw exception?

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

问题描述

catch 块中,如何获取引发异常的行号?

In a catch block, how can I get the line number which threw an exception?

推荐答案

如果您需要的不仅仅是从 Exception.StackTrace 获得的格式化堆栈跟踪的行号,您可以使用 StackTrace 类:

If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

try
{
    throw new Exception();
}
catch (Exception ex)
{
    // Get stack trace for the exception with source file information
    var st = new StackTrace(ex, true);
    // Get the top stack frame
    var frame = st.GetFrame(0);
    // Get the line number from the stack frame
    var line = frame.GetFileLineNumber();
}

请注意,这仅在有可用于程序集的 pdb 文件时才有效.

Note that this will only work if there is a pdb file available for the assembly.

这篇关于如何获取引发异常的行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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