高等 C 語言 -- 模擬 try ... catch

高等 C 語言

簡介

字串

指標與陣列

函數

結構

物件導向

記憶體

檔案

錯誤處理

巨集處理

C 與組合語言

資料結構

動態字串

動態陣列

鏈結串列

雜湊表

開發環境

Make

Cygwin

MinGW

DevC++

wxDevC++

編譯器

gcc 編譯器

TinyCC 編譯器

LCC 編譯器

應用主題

CGI 程式

GNU 程式

視窗程式

影像處理

練習題

訊息

相關網站

參考文獻

最新修改

簡體版

English

程式範例

檔案:trycatch.c

#include <stdio.h>
#include <setjmp.h>
 
enum Error { NoError=0, DivByZero=1, FileError=2 };
 
jmp_buf jumper;
 
void run(char *astr, char *bstr, char *fileName) {  // try 的主程式
  int a = atoi(astr);
  int b = atoi(bstr);
  if (b == 0) // can't divide by 0
    longjmp(jumper, DivByZero);
  int result = a/b;
  FILE *file;
  if ((file=fopen(fileName, "w")) == NULL)
    longjmp(jumper, FileError);
  else {
    fprintf(file, "%d/%d=%d\n", a, b, result);
    printf("save to file %s : %d/%d=%d\n", fileName, a, b, result);
  }
  fclose(file);
}
 
int main(int argc, char *argv[]) {
  int error = setjmp(jumper);             // try
  switch (error) {                        //
    case NoError:                        //
      run(argv[1], argv[2], argv[3]);    //     run();
      break;                            //
    case DivByZero:                        // catch DivByZero:
      printf("Error %d : Divide by zero\n", error);//    ...
      break;                            //
    case FileError:                        // catch FileError:
      printf("Error %d : File error\n", error);    //    ...
      break;                            //
    default:                            // default:
      printf("Error %d:Unhandled error\n", error);//    ...
  } 
}

輸出結果

D:\cp>gcc trycatch.c -o trycatch

D:\cp>trycatch 7 2 div.txt
save to file div.txt : 7/2=3

D:\cp>trycatch 7 0 div.txt
Error 1 : Divide by zero

D:\cp>trycatch 7 0 trycatch.exe
Error 1 : Divide by zero

D:\cp>trycatch 7 1 trycatch.exe
Error 2 : File error

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License