For a C# AI program I use a recursive call to find the best next move (using a 30×30 Array to store the current board state). For each move I make, I want to see which of the possible moves I can make from the new board state will be best… and so on until I either reach an “end of game” position (no further moves possible in that state) or a timer stops the process and no further recursive calls are made (and the “best” known position is returned). This just to explain why I must use recursion (it is not tail recursion) and I cannot use a single (global) board state, but must search all board states possible from the current state.
(Sometimes) I get a System.StackOverflowException. Is there a way to check the available stack space before the next recursive call? Then I could just return the current state as a “best position found so far” and not make the next recursive call. I.e. when the available stack becomes too small it should also count as a base case.
The other option of course, may be to just put each recursive call in a try..catch block and handle the System.StackOverflowException by using it as a base case?
If you really want to go down that path you can use
EnsureSufficientExecutionstackmethod.As others pointed out, starting with .NET 2.0 you cannot catch a
StackOverflowException, however, from the MSDN documentation you know the previous method has the following behavior:When the stack is not large enough according to this method then it will throw an
InsufficientExecutionStackExceptionexception that you can catch.