next up previous contents
Next: 遞迴 Up: 其他 Previous: 型態轉變   Contents

錯誤處理

  1. 程式回傳 0 ,表示沒有錯誤。使用方法:
    1. include errno.h
    2. 全域變數 errno
    3. 函式 perror() 回傳錯誤訊息
    4. 函式 strerror() 回傳 errno 的位址指標
  2. 使用範例
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    
    extern int errno ;
    
    int main ()
    {
       FILE * pf;
       int errnum;
       pf = fopen ("unexist.txt", "rb");
       if (pf == NULL)
       {
          errnum = errno;
          fprintf(stderr, "Value of errno: %d\n", errno);
          perror("Error printed by perror");
          fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
       }
       else
       {
          fclose (pf);
       }
       return 0;
    }
    
  3. 除以 0 錯誤範例
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
       int dividend = 20;
       int divisor = 0;
       int quotient;
     
       if( divisor == 0){
          fprintf(stderr, "Division by zero! Exiting...\n");
          exit(-1);
       }
       quotient = dividend / divisor;
       fprintf(stderr, "Value of quotient : %d\n", quotient );
    
       exit(0);
    }
    
  4. 程式退出狀態
    1. EXIT_SUCCESS 0
    2. EXIT_FAILURE -1
    #include <stdio.h>
    #include <stdlib.h>
    
    main()
    {
       int dividend = 20;
       int divisor = 5;
       int quotient;
     
       if( divisor == 0){
          fprintf(stderr, "Division by zero! Exiting...\n");
          exit(EXIT_FAILURE);
       }
       quotient = dividend / divisor;
       fprintf(stderr, "Value of quotient : %d\n", quotient );
    
       exit(EXIT_SUCCESS);
    }
    



2015-01-16