What is a good general way to catch a StackOverflow exception in C #?

If I have a method that, as I know, can potentially process endlessly, but I cannot reliably predict which conditions / parameters will trigger it, that is a good way in C # to do this:

try { PotentiallyInfiniteRecursiveMethod(); } catch (StackOverflowException) { // Handle gracefully. } 

Obviously, you cannot do this in the main thread, but I have been told several times that this can be done using streams or AppDomain, but I have never seen a working example. Does anyone know how to do this reliably?

+4
source share
2 answers

You can not. From MSDN

Starting with the .NET Framework version 2.0, the exception of the StackOverflowException object cannot be caught by a block attempt and the corresponding process terminated by default. Because of this, users are encouraged to write their own code to detect and prevent stack overflows. For example, if your application depends on recursion, usage by a counter, or a condition condition, complete a recursive loop. Note that the application hosting the common CLR runtime indicates that the CLR unloads the application area in which the stack throws an exception and the corresponding process continues. For more information, see ICLRPolicyManager Interface and Hosting Overview.

+11
source

It is not possible to catch a StackOverflowException, but you can do something with an unhandled exception:

 static void Main() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); } static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e) { try { Exception ex = (Exception)e.ExceptionObject; MessageBox.Show("Whoops! Please contact the developers with the following" + " information:\n\n" + ex.Message + ex.StackTrace, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { Application.Exit(); } } 
+1
source

All Articles