My Question resonated exactly with following question.
break the function after certain time
However, the above question revolves around Python implementation. I am trying to implement the same thing in C++. Here is the code:
#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdexcept>
void handle_alarm( int sig ) {
printf("%d",sig);
throw std::invalid_argument("none");
}
int main() {
for (int i=0; i<10; i++){
signal( SIGALRM, handle_alarm );
printf("Doing normal work %d \n",i);
alarm(120);
try {
for (;;){} // It will be replaced by a function which can take very long time to evaluate.
}
catch(std::invalid_argument& e ) {
continue;
}
}
}
Problem statement
: With each iteration of the loop, a function XYZ, which can take a long time in evaluation, will be called (replaced by a infinite for loop in above code). My objective is to termination the execution of the function, if it takes more than 2 min, and continue to the next iteration.
However, this give me the error terminate called after throwing an instance of 'std::invalid_argument'
. I had also tried to use a custom exception class, but the error persist.
I am unable to figure out whats wrong with this specific implementation, or whether there exist another better approach for it? Any help will be really appreciated.