Problem
How can I get the line number that threw the exception in a catch block?
Asked by MBZ
Solution #1
You may use the StackTrace class to acquire the line number for more than just the structured stack trace you get from 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();
}
It’s worth noting that this will only work if the assembly has a pdb file.
Answered by Quartermeister
Solution #2
Use the Exception in a simple method. The line after the exception description will be returned by the ToString() method.
You can also look through the program debug database, which contains debug information and logs for the entire application.
Answered by SimpleButPerfect
Solution #3
If you don’t have the.PBO file, follow these steps:
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
Alternatively, as an extension to the Exception class.
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;
}
}
Answered by radbyx
Solution #4
stack.
Answered by Darin Dimitrov
Solution #5
Check this one
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
Answered by Ram Maurya
Post is based on https://stackoverflow.com/questions/3328990/how-can-i-get-the-line-number-which-threw-exception