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?