▌第一次閱讀本系列的,可以先看:


▌第一次閱讀例外處理系列,可以先看:


本例外處理系列為【實驗性質】,研究進行中...。
  • 增加 char *error_place 來記錄發生錯誤的位置。
  • 增加 back 巨集來判斷及返回發生錯誤的位置。
  • try 巨集增加了 back_ex 參數,作為 back 巨集使用的返回點。
  • 更改了 catch 巨集使用的形式,更類似真正的 catch ,執行的代碼不再需要放在 catch 的括弧裏。
  • 解決了一個 try 必須獨立對應一個 catch 的問題,現在一個 catch 可對應多個 try 。

【增加】:

char *error_place;
#define back(back_ex) if(!strcmp(error_place, #back_ex)) goto back_ex

【更改】:

#define try(function , ex_name, back_ex) \
\
if(function == -1){\
 error_place = #back_ex; \
 goto ex_name;\
}\
back_ex: \
#define catch(ex_name) \
\
return 0; \
ex_name: 

沒有提及的實現形式沒有變化。


【使用例子】:

int can_not_be_negative(double input) {
 return input < 0 ? -1 : 0;
}

int my_sqrt(double *output, double input) {
 throw(can_not_be_negative(input));
 *output = sqrt(input);
 return 0;
}

int main() {
 double get_output;

 try(my_sqrt(&get_output, -10), ex_can_not_be_negative, ex1);
 try(my_sqrt(&get_output, -20), ex_can_not_be_negative, ex2);
 try(my_sqrt(&get_output, -30), anthor_ex;, ex3);

 /*... any things ...*/

 system("pause");

 catch (ex_can_not_be_negative) {
  printf("[ex_can_not_be_negative] exception is happened!\n");
  printf("Input can't no be negative.\n");
 }
 back(ex1); back(ex2);

 catch (anthor_ex) {
  printf("[anthor_ex] exception is happened!\n");
  printf("Input can't no be negative.\n");
 }
 back(ex3);
}
[ex_can_not_be_negative] exception is happened!
Input can't no be negative.
[ex_can_not_be_negative] exception is happened!
Input can't no be negative.
[anthor_ex] exception is happened!
Input can't no be negative.
Press any key to continue . . .

【問題】:

  • try 使用時的可讀性不高。
  • try 有三個參數,使用方式繁複。
  • catch 結束後須加上 back , back 需要對應、適合的返回點,
    • 多過返回點需要多個 back ,使用方式繁複。
  • 回傳值必須作錯誤碼處理的約定造成麻煩。

有什麼方向、建議、意見麻煩留言,謝謝了。

/images/emoticon/emoticon41.gif