Generally, you can't. StackOverflowException is one of the few exceptions that you cannot catch.
If the exception happens in your own code, the best solution is to convert your algorithm from a recursive call into one that uses a heap-allocated Stack<T> to track depth state and which also allows you to catch cases where the stack's capacity exceeds a threshold (if( stack.Count >= 4000 ) break;.
enum Result {
Found,
NotFound,
Aborted
}
public static Result DepthFirstSearch(Node node) {
Stack<Node> stack = new Stack<Node>();
stack.Push( node );
while( stack.Count > 0 ) {
Node n = stack.Pop();
if( IsNodeWeWant( n ) ) return Result.Found;
foreach(Node child in n.Children) stack.Push( child );
if( stack.Count >= 4000 ) return Result.Aborted;
}
return Result.NotFound;
}
If you feel you must use recursive calls, then add an additional integer parameter to your methods called "depth" (that increases for each recursive call). Within your function you can then check how deep you are and break before you get a stack-overflow.
Example:
enum Result {
Found,
NotFound,
Aborted
}
public static Result DepthFirstSearch(Node node, Int32 depth) {
if( depth >= 4000 ) return Result.Aborted;
if( IsNodeWeWant( node ) ) return Result.Found;
foreach(Node child in node.Children) {
Result result = DepthFirstSearch( child, depth + 1 );
if( result != Result.NotFound ) return result; // return Found or Aborted
}
}
However, if the exception happens outside your code (and you have no means to validate the data to abort the operation before you enter it) then your only option is to create a child process that hosts the buggy code. You can use some form of IPC or shared-memory for communication (though you can't directly share POCOs, at least not without serialization).