本例外處理系列為【實驗性質】,研究進行中...。
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
,使用方式繁複。