maandag 23 mei 2011

Catching StackOverflowException in .NET

A stack overflow in .NET will result into a StackOverflowException.  The curious thing about this exception is that it is thrown at a time that it is too late for the user’s code to handle it.  The stack has already overflown and the code is halted.  There is however a way to catch this before executing.  This method however is only possible when knowing that a stack overflow might occur in the future (for example when doing recursive calls).

A  limitation that you have in safe code is that you cannot get the address location of a variable.  So that leaves out the option of calculating you stack size by subtracting the offset of the stack with the last variable added on the stack (http://stackoverflow.com/questions/1599219/c-catch-a-stack-overflow-exception).  
In C# you could try to work around this by creating unsafe method calls but in VB.NET you would be screwed.

This leaves only one available option and that’s approximating the size of the stack and setting a maximum allowed amount of stackframes.  Throw the StackOverflowException before the CLR does and you’ll be able to catch it.

Public Class OverflowHelper


    Public Shared Sub CheckStackForOverflow()

        Dim stackTrace As StackTrace = New StackTrace()
        Dim maxStackSize = 4000
        Dim nrOfStackFrames = stackTrace.GetFrames().Count
        If nrOfStackFrames > maxStackSize Then
            Throw New StackOverflowException
        End If
    End Sub
End Class

It’s certainly not pretty, I’ll admit that, but it’s the only solution thus far.

Geen opmerkingen:

Een reactie posten