Preserving original StackTrace/LineNumbers in .NET Exceptions

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2009-10-18T14:56:44Z Indexed on 2010/04/04 17:43 UTC
Read the original article Hit count: 370

Filed under:
|
|

Understanding the difference between throw ex and throw, why is the original StackTrace preserved in this example:

    static void Main(string[] args)
    {
        try
        {
            LongFaultyMethod();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
    }

    static void LongFaultyMethod()
    {
        try
        {
            int x = 20;
            SomethingThatThrowsException(x);
        }
        catch (Exception)
        {
            throw;
        }
    }

    static void SomethingThatThrowsException(int x)
    {
        int y = x / (x - x);
    }

But not in this one:

    static void Main(string[] args)
    {
        try
        {
            LongFaultyMethod();
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.StackTrace);
        }
    }

    static void LongFaultyMethod()
    {
        try
        {
            int x = 20;
            int y = x / (x - 20);
        }
        catch (Exception)
        {
            throw;
        }
    }

The second scenario is producing the same output as throw ex would?

In both cases, one expects to see the line number where y is initialized.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about exceptions