0

I recently saw a funny piece of code of a function returning the number five.

This is what it looks like:

namespace Rekursio {
   class Program {
        static void Main(string[] args) {
            Console.WriteLine(getFive());
            Console.ReadLine();
        }

        static int getFive() {
            try {
                return getFive();
            }
            catch (StackOverflowException e) {
                return 5;
            }        
        }
    }
}

I expected this function to return 5 at the end. When running the program, however, I am told that an unhandled StackOverflowException has occurred.

How is this possible? Every situation in which a StackOverflowException is possible is handled.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Fabian F.
  • 31
  • 5
  • 1
    I'm sorry, un-lucky, but your edit kind of messed up the indentation. I know you meant well, but it's not necessary to force your preference onto other users. – Fabian F. Mar 30 '16 at 01:21
  • Thanks PetSerAl, that makes sense! – Fabian F. Mar 30 '16 at 01:21
  • 1
    @PetSerAl [`StackOverflowException is not considered a Corrupted State Exception by .NET`](http://stackoverflow.com/a/28307429/563532) - Take a look [here](http://stackoverflow.com/questions/206820/how-do-i-prevent-and-or-handle-a-stackoverflowexception) for possible solutions – Rob Mar 30 '16 at 01:22
  • Also just a note - even if this *did* work, it would return 0 :) – Rob Mar 30 '16 at 01:23
  • Interesting. Thank you! Why would it return 0, though? – Fabian F. Mar 30 '16 at 01:23
  • 1
    @FabianF. Because `catch (StackOverflowException e)` would catch the exception thrown in the last frame. It would return 5, and then every *other* call to `getFive()` up the stack would return `0`. You'd need to change the code to be `try { return getGive(); }... ` instead – Rob Mar 30 '16 at 01:25
  • 1
    Ah, right. That's what it was initially meant to say; oversight by me. Thanks! I'll edit. – Fabian F. Mar 30 '16 at 01:26

0 Answers0