Home > database >  Is it possible to recover from stack overflow exception and continue executing the next instruction
Is it possible to recover from stack overflow exception and continue executing the next instruction

Time:01-23

For example, this code will throw Stack Overflow because of infinite recursion which will lead to the program crash. Is there a way to handle this exception and avoid the crash and move on to the next instruction execution?

#include <iostream>
#include <exception>

template <typename T>
T sum(T firstValue, T secondValue)
{
        try{
                return firstValue   secondValue;
        }

        catch(const std::exception &e)
        {
                std::cerr << "Caught exception: " << e.what() << '\n';
        }
}

void causeStackOverflow() {
    causeStackOverflow();
}

int main() {

        std::cout << "Sum of 3 & 4 is: " << sum(3, 4) << '\n';

    try {
        causeStackOverflow();
    }

    catch (const std::exception& e) {
        std::cerr << "Caught exception: " << e.what() << '\n'; // If anything can be done here so program can recover and next line can execute?
    }

        std::cout << "Sum of 1 & 2 is: " << sum(1, 2) << '\n';

    return 0;
}

There must be some way which can be used here to do this. Another question would be if it should be done even if it's possible?

Is there any way which can predict with some probability that Stack Overflow is going to happen? So we can take some action to avoid that?

CodePudding user response:

You could refer to the MSDN document to debug stack overflow.

Use the !analyze command to check that we have indeed have a problem with our loop.

dt _TEB can be used to display information.

It is difficult to catch exception because the OS will kill the process. For your reference: C : Getting exception from stack overflow?.

CodePudding user response:

On Windows, with Microsoft Visual C , you can handle a stack overflow using Structured Exception Handling (SEH) like this:

#include <windows.h>
#include <iostream>

void causeStackOverflow() {
    causeStackOverflow();
}

int main() {
    __try {
        causeStackOverflow();
    }
    __except (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW) {
        std::cout << "Handled!\n";
    }
}
  • Related