在捕获块中,如何获得抛出异常的行号?
当前回答
扩展方法
static class ExceptionHelpers
{
public static int LineNumber(this Exception ex)
{
int n;
int i = ex.StackTrace.LastIndexOf(" ");
if (i > -1)
{
string s = ex.StackTrace.Substring(i + 1);
if (int.TryParse(s, out n))
return n;
}
return -1;
}
}
使用
try
{
throw new Exception("A new error happened");
}
catch (Exception ex)
{
//If error in exception LineNumber() will be -1
System.Diagnostics.Debug.WriteLine("[" + ex.LineNumber() + "] " + ex.Message);
}
其他回答
更新到答案
// 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(st.FrameCount-1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
如果你的堆栈跟踪大于1,它应该是:
var st = new StackTrace(es, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount - 1);
//从栈帧中获取行号 var line = frame.GetFileLineNumber();
如果您需要的行号不仅仅是从Exception中获得的格式化堆栈跟踪。你可以使用StackTrace类:
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文件可用时才有效。
Convert.ToInt32(ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
这将给出异常行no。
我尝试使用@davy-c的解决方案,但有一个异常“系统。输入字符串的格式不正确。’”,这是由于仍然有文本超过行号,我修改了他发布的代码,并提出:
int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
这适用于我在VS2017 c#。
推荐文章
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Visual Studio:如何打破处理异常?
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法