Search code examples
c#.netthrow

Rethrow an Exception with correct line numbers in the stack trace


You are apparently able to rethrow an Exception without discarding the stack trace in .NET.

However it doesn't appear to be working.

Basic usage I'm following is thus:

    [WebMethod]
    public void ExceptionTest()
    {
        try
        {
            throw new Exception("An Error Happened");
        }
        catch (Exception ex)
        {
            evlWebServiceLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
            throw;
        }
    }

Problem is, the line number in the exception in the line of the throw; line, not the original throw new line.

I've tested it in a simple exe project and without the logging to the windows log line. It doesn't make any difference, the stack trace always has the wrong line number in it, making it less than useful.

Why is it doing this? How do I do it correctly?


Solution

  • You do not lose original exception if you place it in an inner exception.

    [WebMethod]
    public void ExceptionTest()
    {
        try
        {
            throw new Exception("An Error Happened");
        }
        catch (Exception ex)
        {
            evlWebServiceLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
            throw new Exception("Your message", ex);
        }
    }