I don’t need a lesson in switching from recursive to non-recursive means, I just want to know why we can’t deal with this type of exception. Regardless, I’m using recursive functions on very large lists.
I have written code to attempt to catch StackOverFlowExceptions:
try { recursiveFxn(100000); }
catch(Exception){}
private void recursiveFxn(int countdown)
{
if (countdown > 0)
recursiveFxn(countdown - 1);
else
throw new Exception("lol. Forced exception.");
}
But still I get program crashes (in both NUnit and a webpage I’m running). Why isn’t the exception caught?
Since .NET Framework 2.0,
StackOverflowExceptioncannot be caught. This is because it is considered a bad practice. Quoting the MSDN documentation:Now, the only way to catch a
StackOverflowExceptionis when it was thrown by user code, as explained in a blog by Jared Parsons. Other than that, by hosting the CLR, you can handle (but not catch) aStackOverflowExceptionand devise a way to let the execution of your program continue.Note that because the stack is unwound when an exception occurs, in pre-2.0 versions of .Net the stack would actually be much shorter when the
StackOverflowExceptionis handled, making it possible to do so without generating anotherStackOverflowException.