【问题标题】:C error handling at end of program程序结束时的 C 错误处理
【发布时间】:2016-09-05 17:58:30
【问题描述】:

我已经阅读了很多关于 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)
}

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

【问题讨论】:

  • 嘿?如果出现问题,为什么要继续?
  • int status = N; /* ... */ exit(status);? (或者更好的return

标签: c exit stderr


【解决方案1】:

好吧,如果你想继续,你不必打电话给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);
}

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

【讨论】:

  • 感谢您的提示!当然,我会记住不要在代码的某些关键位置继续执行。
【解决方案2】:

exitint 作为状态,您可以将此状态存储在一个变量中,并在末尾使用此值调用exit

int main(void)
{
    int res = EXIT_SUCCESS;

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

【讨论】:

  • 谢谢!正如其他人所指出的那样,C 中没有特定的 try-catch。我将尝试使用指针,因为我还有其他具有如此轻微“错误”的函数(当然有些会立即退出)。跨度>
猜你喜欢
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2018-10-30
  • 2014-12-25
相关资源
最近更新 更多