I have read through a lot of tutorials and beginner questions on error handling in C. They all (well most) seem to go in this direction:
int main(){
if(condition){
fprintf(stderr, "Something went wrong");
exit(EXIT_FAILURE); // QUIT THE PROGRAM NOW, EXAMPLE: ERROR OPENING FILE
}
exit(0)
}
My question: is there any particular function in C that lets me catch an error, but only affect the status of the program (main) when it exits? Example of my idea:
int main(){
if(condition){
fprintf(stderr, "Something went wrong");
// Continue with code but change exit-status for the program to -1 (EXIT_FAILURE)
}
exit(IF ERROR CATCHED = -1)
}
Or do I have to create some custom function or use some pointer?
Well, you don't have to call exit()
if you want to continue, right?
You can use a variable that affects main()'s exit code.
#include <stdio.h>
int main(void){
int main_exit_code = EXIT_SUCCESS;
if(condition){
fprintf(stderr, "Something went wrong");
main_exit_code = -1; /* or EXIT_FAILURE */
}
return (main_exit_code);
}
But do note that depending on the kind of errors you encounter, it may not make sense to continue execution in all cases. So, I'll leave that to you decide.