C# catch a stack overflow exception
Asked Answered
S

10

137

I have a recursive call to a method that throws a stack overflow exception. The first call is surrounded by a try catch block but the exception is not caught.

Does the stack overflow exception behave in a special way? Can I catch/handle the exception properly?

Not sure if relevant, but additional information:

  • the exception is not thrown in the main thread

  • the object where the code is throwing the exception is manually loaded by Assembly.LoadFrom(...).CreateInstance(...)

Shaeffer answered 21/10, 2009 at 7:15 Comment(4)
@RichardOD, sure I fix the bug because it was a bug. However the issue can appear in a different way and I wan to handle itShaeffer
Agreed, a stack overflow is a serious error that can't be caught because it shouldn't be caught. Fix the broken code instead.Turki
@RichardOD: If one wants to design e.g. a recursive-descent parser and not impose artificial limits on depth beyond those actually required by the host machine, how should one go about it? If I had my druthers, there would be a StackCritical exception which could be explicitly caught, which would be fired while there was still a little stack space left; it would disable itself until it was actually thrown, and could then not be caught until a safe amount of stack space remained.Analyzer
This question is useful -- I want to fail a unit test if a stack overflow exception occurs -- but NUnit just moves the test to the "ignored" category instead of failing it like it would with other exceptions -- I need to catch it and do an Assert.Fail instead. So seriously -- how do we go about this?Botha
F
119

Starting with 2.0 a StackOverflow Exception can only be caught in the following circumstances.

  1. The CLR is being run in a hosted environment* where the host specifically allows for StackOverflow exceptions to be handled
  2. The stackoverflow exception is thrown by user code and not due to an actual stack overflow situation (Reference)

*"hosted environment" as in "my code hosts CLR and I configure CLR's options" and not "my code runs on shared hosting"

Fuchsia answered 21/10, 2009 at 7:20 Comment(6)
If it can't be caught in any relevant scebario, why does the StackoverflowException object exist?Seeder
@Seeder for at least a couple of reasons. 1) Is that it could be caught, kind of, in 1.1 and hence had a purpose. 2) It can still be caught if you are hosting the CLR so it's still a valid exception typeFuchsia
If it can't be caught... Why doesn't the windows event explaining what happened include the full stack trace by default?Hellkite
How does one go about allowing StackOverflowExceptions to be handled in a hosted environment? Reason I'm asking is because I run a hosted environment, and I'm having this exact problem, where it destroys the entire app pool. I would much rather have it abort the thread, where it can unwind back up to the top, and I can then log the error and continue on without having all the apppool's threads killed.Salve
Starting with 2.0 ..., I'm curios, what is preventing them from catching SO and how it was possible 1.1 (you mentioned that in your comment)?Crutchfield
@Salve same requirement hereRovelli
B
52

The right way is to fix the overflow, but....

You can give yourself a bigger stack:-

using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();

You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.

Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-

class Program
{
    static int n;
    static int topOfStack;
    const int stackSize = 1000000; // Default?

    // The func is 76 bytes, but we need space to unwind the exception.
    const int spaceRequired = 18*1024; 

    unsafe static void Main(string[] args)
    {
        int var;
        topOfStack = (int)&var;

        n=0;
        recurse();
    }

    unsafe static void recurse()
    {
        int remaining;
        remaining = stackSize - (topOfStack - (int)&remaining);
        if (remaining < spaceRequired)
            throw new Exception("Cheese");
        n++;
        recurse();
    }
}

Just catch the Cheese. ;)

Beauregard answered 21/10, 2009 at 11:33 Comment(4)
Cheese is far from specific. I'd go for throw new CheeseException("Gouda");Lactoprotein
@Lactoprotein Whilst there's no doubt that Gouda is an exceptional cheese it should be a RollingCheeseException("Double Gloucester") really see cheese-rolling.co.ukBeauregard
lol, 1) fixing is not possible because without catching it you often don't know where it happens 2) increasing the Stacksize is useless with endless recursion andm 3) checking the Stack in the right location is like the firstAddendum
but I'm lactose intolerantNide
K
47

From the MSDN page on StackOverflowExceptions:

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.

Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, see ICLRPolicyManager Interface and Hosting the Common Language Runtime.

Koala answered 21/10, 2009 at 7:19 Comment(0)
M
31

As several users have already said, you can't catch the exception. However, if you're struggling to find out where it's happening, you may want to configure visual studio to break when it's thrown.

To do that, you need to open Exception Settings from the 'Debug' menu. In older versions of Visual Studio, this is at 'Debug' - 'Exceptions'; in newer versions, it's at 'Debug' - 'Windows' - 'Exception Settings'.

Once you have the settings open, expand 'Common Language Runtime Exceptions', expand 'System', scroll down and check 'System.StackOverflowException'. Then you can look at the call stack and look for the repeating pattern of calls. That should give you an idea of where to look to fix the code that's causing the stack overflow.

Module answered 21/10, 2009 at 8:29 Comment(2)
Where is Debug - Exceptions in VS 2015?Weirick
Debug - Windows - Exception SettingsModule
B
17

As mentioned above several times, it's not possible to catch a StackOverflowException that was raised by the System due to corrupted process-state. But there's a way to notice the exception as an event:

http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Starting with the .NET Framework version 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

Nevertheless your application will terminate after exiting the event-function (a VERY dirty workaround, was to restart the app within this event haha, havn't done so and never will do). But it's good enough for logging!

In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.

Boru answered 28/7, 2011 at 9:33 Comment(0)
C
7

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

Christianchristiana answered 21/10, 2009 at 7:18 Comment(2)
From CLR 2.0 a StackOverflowException terminates the process by default.Christianchristiana
No. You can catch OOM and in some cases it might make sense to do so. I don't know what you mean by thread disappearing. If a thread has an unhandled exception the CLR will terminate the process. If your thread completes its method it will be cleaned up.Christianchristiana
S
6

You can't. The CLR won't let you. A stack overflow is a fatal error and can't be recovered from.

Serbocroatian answered 21/10, 2009 at 7:19 Comment(2)
So how do you make a Unit Test fail for this exception if instead of being catchable it crashes the unit test runner instead?Botha
@BrainSlugs83. You don't, because that's a silly idea. Why are you testing if your code fails with a StackOverflowException anyway? What happens if the CLR changes so it can handle a deeper stack? What happens if you call your unit tested function somewhere that already has a deeply nested stack? It seems like something that's not able to be tested. If you are trying to throw it manually, choose a better exception for the task.Serbocroatian
M
6

You can't as most of the posts are explaining, let me add another area:

On many websites you will find people saying that the way to avoid this is using a different AppDomain so if this happens the domain will be unloaded. That is absolutely wrong (unless you host your CLR) as the default behavior of the CLR will raise a KillProcess event, bringing down your default AppDomain.

Mountaineer answered 11/2, 2010 at 8:39 Comment(0)
B
4

It's impossible, and for a good reason (for one, think about all those catch(Exception){} around).

If you want to continue execution after stack overflow, run dangerous code in a different AppDomain. CLR policies can be set to terminate current AppDomain on overflow without affecting original domain.

Beading answered 21/10, 2009 at 7:33 Comment(2)
The "catch" statements wouldn't really be a problem, since by the time a catch statement could execute the system would have rolled back the effects of whatever had tried to use two much stack space. There's no reason catching stack overflow exceptions would have to be dangerous. The reason they're such exceptions can't be caught is that allowing them to be caught safely would require adding some extra overhead to all code that uses the stack, even if it doesn't overflow.Analyzer
At some point the statement is not well thought. If you can't catch the Stackoverflow you maybe never know WHERE it happened in a production environment.Krauss
S
1

You can check stack before executing method with RuntimeHelpers.EnsureSufficientExecutionStack method msdn.

using System.Runtime.CompilerServices;

class Program
{
   static void Main()
   {
      try
      {
          Recursion();
      }
      catch (InsufficientExecutionStackException e)
      {
      }
   }

   static void Recursion()
   {
       RuntimeHelpers.EnsureSufficientExecutionStack();
       Recursion();
   }
}
Sternutation answered 29/4, 2023 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.