程序结束时的C错误处理

时间:2016-09-05 17:58:31

标签: c exit stderr

我已经阅读了很多有关C中错误处理的教程和初学者问题。他们(大多数)似乎都朝这个方向发展:

int main(){

if(condition){
    fprintf(stderr, "Something went wrong");
    exit(EXIT_FAILURE); // QUIT THE PROGRAM NOW, EXAMPLE: ERROR OPENING FILE
}

exit(0)
}

我的问题:C中是否有任何特定功能可以捕获错误,但只会影响程序退出时的状态(主要)?我的想法的例子:

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)
}

或者我是否必须创建一些自定义函数或使用某些指针?

2 个答案:

答案 0 :(得分:4)

好吧,如果你想继续,你不必打电话给exit(),对吗? 您可以使用影响main()退出代码的变量。

#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);
}

但请注意,根据您遇到的错误类型,在所有情况下继续执行可能没有意义。所以,我会留给你决定。

答案 1 :(得分:2)

exit获取int作为状态,您可以将此状态存储在变量中,并在结尾处使用此值调用exit

int main(void)
{
    int res = EXIT_SUCCESS;

    if (condition) {
       fprintf(stderr, "Something went wrong");
       res = EXIT_FAILURE;
    }
    /* Continue with code */
    exit(res);
}