C# catch a stack overflow exception

前端 未结 9 1018
生来不讨喜
生来不讨喜 2020-11-22 09:12

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

9条回答
  •  Happy的楠姐
    2020-11-22 09:50

    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. ;)

提交回复
热议问题