Throwing an exception more than once loses the original stack trace

I played with Exceptions to learn more about how to use them correctly. So far, I know that it throwkeeps the original stack trace; throw new CustomException(...)usually used when you want to add additional information about an exception that occurred or add / change a message, or even change the type of the Exception itself; and throw exshould never be used unless I want to lose the original stack trace.

So, I wrote a small program in which I could catch and repeat the exception several times, adding something to the original message.

public class Sample
{
    static void Main(string[] args)
    {
        new Tester().FirstCall();
    }
}

public class Tester
{
    public void FirstCall()
    {
        try
        {
            SecondCall();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            Console.WriteLine(e.Message);
        }
    }

    public void SecondCall()
    {
        try
        {
            ThirdCall();
        }
        catch (GoodException ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    public void ThirdCall()
    {
        try
        {
            FourthCall();
        }
        catch (ArithmeticException ae)
        {
            throw new GoodException("Arithmetic mistake: " + ae.Message, ae);
        }
    }

    public void FourthCall()
    {
        int d = 0;
        int x = 10 / d;
    }
}

Where GoodExceptionis the special exception implemented correctly .

I expect the console to display something like this:

   at PlayingWithExceptions.Tester.FourthCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 67
   at PlayingWithExceptions.Tester.ThirdCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 59
   at PlayingWithExceptions.Tester.SecondCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 41
   at PlayingWithExceptions.Tester.FirstCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 25
Arithmetic mistake: Attempted to divide by zero.

:

   at PlayingWithExceptions.Tester.SecondCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 41
   at PlayingWithExceptions.Tester.FirstCall() in d:\Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs:line 25
Arithmetic mistake: Attempted to divide by zero.

- . , catch InnerException, . , throw , , , , ( ).

, : , ?

: , - FourthCall try/catch ( ), FirstCall.

+4
2

"", , . "" Inner - , SecondCall, .

, . , , Exception. , . , , , - .

+6

, . throw " , , . .

0

Source: https://habr.com/ru/post/1542402/


All Articles