在catch
块中,如何获取抛出异常的行号?
发布于 2010-07-25 19:52:25
如果除了从Exception.StackTrace获得的格式化堆栈跟踪之外,还需要行号,则可以使用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文件时,这才会起作用。
发布于 2010-07-25 19:32:45
简单的方法,使用Exception.ToString()
函数,它会返回异常描述后的行。
您还可以检查程序调试数据库,因为它包含有关整个应用程序的调试信息/日志。
发布于 2015-02-13 17:15:36
如果您没有.PBO
文件:
C#
public int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
Vb.net
Public Function GetLineNumber(ByVal ex As Exception)
Dim lineNumber As Int32 = 0
Const lineSearch As String = ":line "
Dim index = ex.StackTrace.LastIndexOf(lineSearch)
If index <> -1 Then
Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
If Int32.TryParse(lineNumberText, lineNumber) Then
End If
End If
Return lineNumber
End Function
或者作为Exception类的扩展
public static class MyExtensions
{
public static int LineNumber(this Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
https://stackoverflow.com/questions/3328990
复制相似问题