3

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?

Pavoo
  • 75
  • 2
  • 6

2 Answers2

5

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Thanks for the tips! And of course I'll keep in mind to not continue execution on some critical places of the code. – Pavoo Sep 05 '16 at 18:21
2

exit takes an int as status, you can store this status in a variable and call exit with this value at the end:

int main(void)
{
    int res = EXIT_SUCCESS;

    if (condition) {
       fprintf(stderr, "Something went wrong");
       res = EXIT_FAILURE;
    }
    /* Continue with code */
    exit(res);
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 1
    Thanks! As others have pointed out, there is no specific try-catch in C. I'll have a go with a pointer, because I have other functions with such minor "errors" (and of course some that will exit immediately). – Pavoo Sep 05 '16 at 18:19