StackOverflow exception handling -- ideas ?
I'll admit it, sometimes my code has bugs -- hopefully all caught before release, but always the first cut has bugs. Today I hit one that made me think about something I may have been doing wrong for some time.
It's all about StackOverflowException. When one of these is thrown, you must rethrow it, and let the CLR terminate your application. Why? Well, as I've learned (and the name suggests), your app is now in an unstable state. Besides the obvious problems of being out of stack space, the not-so-obvious hits you -- finally blocks require stack space! Yes, this means that none of your finally blocks have been / will be executed from the time the exception happened going forward.
So, in the way past, I used to catch System.Exception in code where I knew I could simply drop whatever operation I was doing and recover. Oops, bad Idea -- you can't recover from everything (perhaps more on that later).
Now, I put cleanup in the finally block, logging and problem handling in the catch block, and rethrow anything I don't know how to handle (if I catch it at all). I thought that was great, until today.
If I'm using some precious resource that must be released or brought to a known state, I used to put that in the finally block. But if something goofy happens (Murphy insists that it will) and a StackOverflowException is thrown, then my finally is not called! Yikes!
Do I need cleanup in two places (catch and finally? catch and end of try block? )? I can't centralize it into a method, as I can't call into any methods during a StackOverflowException. I suppose I could say "that probably won't happen" and ignore it, but on a machine that is never rebooted, it might happen. I can live with monitoring my app and restarting it if the CLR must terminate it, but I can't live with my app slowly bringing the server into an unstable state. Any thoughts?
P.S - any thoughts on how to log a StackOverflowException?