Search code examples
c#exceptiontry-catchthrow

C# not entering exception after using throw


I'm a beginner programmer and I have been faced with exceptions recently. I've done this small test below and the output I received was not the same as the one I expected.

static void Main(string[] args)
    {
        ushort var = 65535;
        try
        {
            checked { var++; }
        }
        catch (OverflowException)
        {
            Console.WriteLine("Hello!");
            throw;
        }
        catch
        {
            Console.WriteLine("Here I am!");

        }
    }

I was expecting the program to do the following:

  • Try to var++, fail and create an OverflowException;
  • Enter Catch (OverflowException) and write "Hello!";
  • Throw an Exception and enter catch;
  • Write "Here I am!".

However, I only got on screen "Hello!".

EDIT: Thanks to those who commented. I think I'm starting to understand. However, my confusion originated because of this book I'm reading: C# 4.0.

I could show the text, however it is in Portuguese. I'm going to translate what it says: "Sometimes it is useful to propagate the exception through more than one catch. For example, let's suposse it is necessary to show a specific error message due to the fact that the "idade" is invalid, but we still need to close the program, being that part in the global catch. In that case, it is necessary to propagate the exception after the execution of the first catch block. To do that, you only need to do a simple throw with no arguments."

Example from the book

In this example of the book you can see the programmer do the same thing I did. At least it looks like it. Am I missing something? Or is the book wrong?

Hope you can help me. Thanks!


Solution

  • You'll get the output you expected if you nest try/catch blocks:

    static void Main(string[] args)
    {
        try
        {
            ushort var = 65535;
            try
            {
                checked { var++; }
            }
            catch (OverflowException)
            {
                Console.WriteLine("Hello!");
                throw;
            }
        }
        catch
        {
            Console.WriteLine("Here I am!");
        }
    }