我已经阅读了很多关于 C 错误处理的教程和初学者问题。它们(大多数)似乎都朝着这个方向发展:
int main(){
if(condition){
fprintf(stderr, "Something went wrong");
exit(EXIT_FAILURE); // QUIT THE PROGRAM NOW, EXAMPLE: ERROR OPENING FILE
}
exit(0)
}
Run Code Online (Sandbox Code Playgroud)
我的问题: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)
}
Run Code Online (Sandbox Code Playgroud)
或者我是否必须创建一些自定义函数或使用一些指针?
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);
}
Run Code Online (Sandbox Code Playgroud)
但请注意,根据您遇到的错误类型,在所有情况下继续执行可能没有意义。所以,我将让你决定。