C# - 获取引发的异常行号 [英] C# - get line number which threw exception

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

问题描述

块,我怎样才能得到它抛出一个异常?

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

推荐答案

如果你需要的不仅仅是格式化的堆栈跟踪越多,你从Exception.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.

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

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