C程序中的错误处理

虽然C不提供对错误处理(或异常处理)的直接支持,但有一些方法可以在C中完成错误处理。程序员必须首先防止错误,并测试函数的返回值。 很多C函数调用在出现错误时会返回-1或NULL,因此可以很容易地使用例如“if语句”对这些返回值进行快速测试。例如,在 套接字编程 ,检查socket()、listen()等函数的返回值,以查看是否存在错误。

null

示例:套接字编程中的错误处理

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
   perror("socket failed");
   exit(EXIT_FAILURE);
}

C语言中错误处理的不同方法

  1. 全局变量errno: 在C中调用函数时,名为errno的变量会自动分配一个代码(值),该代码可用于识别遇到的错误类型。它是一个全局变量,指示在任何函数调用期间发生的错误,并在头文件errno中定义。H errno的不同代码(值)意味着不同类型的错误。下面列出了几个不同的errno值及其对应的含义:
    errno value       Error
    1             /* Operation not permitted */
    2             /* No such file or directory */
    3             /* No such process */
    4             /* Interrupted system call */
    5             /* I/O error */
    6             /* No such device or address */
    7             /* Argument list too long */
    8             /* Exec format error */
    9             /* Bad file number */
    10            /* No child processes */
    11            /* Try again */
    12            /* Out of memory */
    13            /* Permission denied */
    
    

    // C implementation to see how errno value is
    // set in the case of any error in C
    #include <stdio.h>
    #include <errno.h>
    int main()
    {
    // If a file is opened which does not exist,
    // then it will be an error and corresponding
    // errno value will be set
    FILE * fp;
    // opening a file which does
    // not exist.
    fp = fopen ( "GeeksForGeeks.txt" , "r" );
    printf ( " Value of errno: %d " , errno );
    return 0;
    }

    
    

    输出:

    Value of errno: 2
    

    注意:这里errno设置为2,这意味着没有这样的文件或目录。在在线IDE上,它可能会给出错误号13,表示权限被拒绝。

  2. perror()和strerror() 上面的errno值表示遇到的错误类型。 如果需要显示错误描述,则有两个功能可用于显示与errorno关联的文本消息。功能包括:
    • 佩罗尔: 它显示传递给它的字符串,后跟冒号、空格,然后是当前errno值的文本表示形式。 语法:
      void perror (const char *str)
      str: is a string containing a custom message
      to be printed before the error message itself.
    • strerror(): 返回指向当前errno值的文本表示形式的指针。 语法:
      char *strerror (int errnum)
      errnum: is the error number (errno).

    // C implementation to see how perror() and strerror()
    // functions are used to print the error messages.
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    int main ()
    {
    FILE *fp;
    // If a file is opened which does not exist,
    // then it will be an error and corresponding
    // errno value will be set
    fp = fopen ( " GeeksForGeeks.txt " , "r" );
    // opening a file which does
    // not exist.
    printf ( "Value of errno: %d " , errno );
    printf ( "The error message is : %s" ,
    strerror ( errno ));
    perror ( "Message from perror" );
    return 0;
    }

    
    

    输出: 在个人桌面上:

    Value of errno: 2
    The error message is : No such file or directory
    Message from perror: No such file or directory
    

    在在线IDE上:

     Value of errno: 13
    The error message is : Permission denied
    

    注: 函数peror()显示传递给它的字符串,后跟冒号和当前errno值的文本消息。

  3. 退出状态: C标准指定了两个常量:EXIT_SUCCESS和EXIT_FAILURE,可以传递给EXIT(),分别表示终止成功或失败。这些是stdlib中定义的宏。H

    // C implementation which shows the
    // use of EXIT_SUCCESS and EXIT_FAILURE.
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <stdlib.h>
    int main ()
    {
    FILE * fp;
    fp = fopen ( "filedoesnotexist.txt" , "rb" );
    if (fp == NULL)
    {
    printf ( "Value of errno: %d" , errno );
    printf ( "Error opening the file: %s" ,
    strerror ( errno ));
    perror ( "Error printed by perror" );
    exit (EXIT_FAILURE);
    printf ( "I will not be printed" );
    }
    else
    {
    fclose (fp);
    exit (EXIT_SUCCESS);
    printf ( "I will not be printed" );
    }
    return 0;
    }

    
    

    输出:

    Value of errno: 2
    Error opening the file: No such file or directory
    Error printed by perror: No such file or directory
    
  4. 除以零误差: C程序员的一个常见陷阱是在除法命令之前不检查除数是否为零。除零导致未定义的行为,没有C语言构造可以对此做任何事情。你最好的办法是通过检查分母,一开始不要被零除。

    // C program to check  and rectify
    // divide by zero condition
    #include<stdio.h>
    #include <stdlib.h>
    void function( int );
    int main()
    {
    int x = 0;
    function(x);
    return 0;
    }
    void function( int x)
    {
    float fx;
    if (x==0)
    {
    printf ( "Division by Zero is not allowed" );
    fprintf (stderr, "Division by zero! Exiting..." );
    exit (EXIT_FAILURE);
    }
    else
    {
    fx = 10 / x;
    printf ( "f(x) is: %.5f" , fx);
    }
    }

    
    

    输出:

    Division by Zero is not allowed

本文由 马扎尔·伊玛目·汗 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享