263

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

5

15 Answers 15

348

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();
}

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

11
  • 3
    ?(New StackTrace(ex, True)).GetFrame(0).GetFileLineNumber() for VB single line from the immediate window.
    – Jonathan
    Oct 18, 2012 at 9:55
  • 45
    C# one liner: int line = (new StackTrace(ex, true)).GetFrame(0).GetFileLineNumber();
    – gunwin
    Aug 23, 2013 at 12:15
  • 25
    This always returns 0 for me. Is this caused by not having a pdb file? What is it and how to get it? (I am using ASP.net)
    – Brabbeldas
    Sep 27, 2013 at 9:58
  • 21
    Why are you using GetFrame(0)? I would think that you should be using GetFrame(FrameCount-1). Jan 15, 2015 at 9:24
  • 14
    I've found @DewaldSwanepoel suggestion of using GetFrame(st.FrameCount-1) to be far more reliable. Feb 23, 2016 at 21:03
112

Simple way, use the Exception.ToString() function, it will return the line after the exception description.

You can also check the program debug database as it contains debug info/logs about the whole application.

8
  • Well MSDN thinks differently, that it "Creates and returns a string representation of the current exception": msdn.microsoft.com/en-us/library/…
    – Prokurors
    Jul 21, 2014 at 9:05
  • 1
    You get something similar to: System.Exception: Test at Tests.Controllers.HomeController.About() in c:\Users\MatthewB\Documents\Visual Studio 2013\Projects\Tests\Tests\Controllers\HomeController.cs:line 22 Dec 9, 2015 at 10:27
  • 6
    This should be the accepted answer. I always went for ex.message and wondered why stupid VB.net isn't able to get the same information as in Java. Apr 8, 2016 at 14:45
  • 4
    It is insane that this answer does not have more upvotes. This is simple, works reliably, and does not come with the PDB caveats. Jun 1, 2017 at 15:49
  • 19
    Exception.Message is dead to me. Never again. Mar 9, 2018 at 16:31
33

If you don't have the .PBO file:

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

Or as an extentions on 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;
    }
}   
3
  • 9
    Unfortunately will not work in not english OS ("line" word depends on locale). Sep 14, 2015 at 15:17
  • 2
    @KvanTTT You could use Regex.Match with :[^ ]+ (\d+) for the same effect. Mar 2, 2017 at 13:34
  • This answer does not work for me, as ex.StackTrace has no :line and I do not have the PDB file. Feb 26, 2020 at 16:46
24

You could include .PDB symbol files associated to the assembly which contain metadata information and when an exception is thrown it will contain full information in the stacktrace of where this exception originated. It will contain line numbers of each method in the stack.

2
10

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();
4

I added an extension to Exception which returns the line, column, method, filename and message:

public static class Extensions
{
    public static string ExceptionInfo(this Exception exception)
    {

        StackFrame stackFrame = (new StackTrace(exception, true)).GetFrame(0);
        return string.Format("At line {0} column {1} in {2}: {3} {4}{3}{5}  ",
           stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber(),
           stackFrame.GetMethod(), Environment.NewLine, stackFrame.GetFileName(),
           exception.Message);

    }
}
4
Convert.ToInt32(ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));  

This will give the Exception line no.

3

I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:

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 ", ""));

This works for me in VS2017 C#.

2

Update to the answer

    // 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

Extension Method

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;
    }
}

Usage

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);
}
1

Working for me:

var st = new StackTrace(e, true);

// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();
1

Line numbers will be included in the stack trace if the library which generated the exception is compiled with debug symbols. This can be a separate file (*.pdb) or embedded in the library.

For .NET Core, .NET 5 and later, to have full exception line numbers in release builds, configure the project as follows:

<PropertyGroup>    
  <DebugSymbols>true</DebugSymbols>
  <DebugType>embedded</DebugType>

    <!-- Only enable the following if the line numbers mismatch -->
    <!--<Optimize>false</Optimize>-->
    
    <!--
      Additional properties which may impact how printed line numbers match the source code line numbers are listed here:
      https://learn.microsoft.com/en-us/dotnet/core/run-time-config/compilation
    -->
</PropertyGroup>

The above configuration will include debug symbols directly with the built files, which can be published as nugets.

An alternative to the above is to restore debug packages together with the main nuget packages, which is currently not yet supported: https://github.com/NuGet/Home/issues/9667

Now get the exception line numbers:

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();
}
1

If your stack trace is bigger than one it should be:

var st = new StackTrace(es, 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();

0
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        int line1 = 1;
        int line2 =int.Parse("Test");
    }
    catch (Exception ex)
    {
        var st =new System.Diagnostics.StackTrace(ex,true);
        var frame = st.GetFrame(st.FrameCount - 1);
        var linenumber = frame.GetFileLineNumber();
    }
}
1
  • The accepted answer does not work properly in the console application project, so the line number is 0. The row number comes with the code I wrote.
    – Aydin Kir
    Mar 2, 2023 at 14:55
-7

In Global.resx file there is an event called Application_Error

it fires whenever an error occurs,,you can easily get any information about the error,and send it to a bug tracking e-mail.

Also i think all u need to do is to compile the global.resx and add its dll's (2 dlls) to your bin folder and it will work!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.