How do I catch a StackOverflowException
?
I have a program that allows the user to write scripts, and when running arbitrary user-code I may get a StackOverflowException
. The piece running user code is obviously surrounded with a try
-catch
, but stack overflows are uncatchable under normal circumstances.
I've looked around and this is the most informative answer I could find, but still led me to a dead end; from an article in the BCL team's blog I found that I should use RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup
to call the code and the delegate that would get called even after a stack overflow, but when trying, the process gets terminated with the stack overflow message without the delegate ever getting called. I've tried adding PrePrepareMethodAttribute
on the handler method but that didn't change anything.
I've also tried using an AppDomain and handling both the UnhandledException
and the DomainUnload
event - but the entire process gets killed on stack overflows. The same happens even if I throw new StackOverflowException();
manually and not get an actual stack overflow.