捕獲數學函式異常

2021-08-30 02:52:52 字數 2872 閱讀 2450

捕獲數學函式異常

假如我們要用乙個數學函式,比如反正弦函式asin(x),如果變元x的值是由使用者提供或某個中間結果,則在呼叫時必須判斷其取值範圍是合理,是否滿|x|<=1?即

if(fabs(x)<=1)

y=asin(x);

else

y=…

對數函式也可作類似的處理。但是如果遇到冪函式pow(x,y)時,問題就不那麼簡單了。仔細分析將發現:yx

負小數負整數0整數

小數負小數

無意義有意義

有意義有意義

無意義負整數

無意義有意義

有意義有意義

無意義0

無意義無意義

有意義有意義

有意義整數

有意義有意義

有意義有意義

有意義小數

有意義有意義

有意義有意義

有意義例如:pow(-1.2,-1.2)=-1.#ind。如果要程式設計處理,至少需要六個if語句。即使如此,也有麻煩:如何判斷乙個double型的變元的值是整數還是小數?

為了處理數學函式運算中出現的異常,vc++提供了乙個函式_mather,其原型在中:

int _matherr( struct _exception *except );
為了利用此函式,只需在應用數學函式的地方定義乙個這樣的函式,例如
#include #include void main()

int _matherr(struct _exception *except)

; printf("error function name is %s\n",except->name);

printf("the varianbles arg1=%g,arg2=%g\n",except->arg1,except->arg2);

printf("the error type = %s\n",errorstring[except->type]);

printf("the error value=%g\n",except->retval);

except->retval=1234;

printf("after handling error value=%g\n",except->retval);

return 1;

}

編譯、執行,結果為

-0.813008

error function name is pow

the varianbles arg1=-1.23,arg2=-1.1

the error type = _sing

the error value=-1.#ind

after handling error value=1234

1234

press any key to continue

第一行為-1.23的倒數,第二~六兩行是_matherr函式的輸出,第七行是主函式的輸出。

也許有人會說,main函式並沒有呼叫_matherr函式,為什麼會出現這種情況呢?這就是vc++編譯器為我們做的事情了。它很有可能在數學函式中設定了跳轉來實現異常處理,當數學庫中的符點函式探測到乙個錯誤時,就呼叫此函式。下面是有關_matherr函式的一些說明:

1、返回值:型別是整型的。按慣例,0返回值用來標誌乙個錯誤,非0值標誌成功。如果返回0,則錯誤資訊可被顯示,錯誤序號被正確設定。如果返回非0值,沒有顯示錯誤資訊,錯誤序號也保持不變。

2、引數:except指標指向乙個包含錯誤資訊的結構 struct _exception。

_exception結構包含有如下資料成員:

int type 異常型別;

char *name 出錯函式名;

double arg1, arg2 函式的第一和第二(如果有的話)引數;

double retval 函式的返回值。

注意:數學函式的錯誤型別定義如下:

_domain 變元定義域錯誤;

_sing 變元奇異點錯誤;

_overflow 溢位錯誤;

_ploss 精度部分遺失;

_tloss 精度丟失;

_underflow 下溢錯誤,結果太小,無發表示。

/* matherr.c illustrates writing an error routine for math 

* functions. the error function must be:

* _matherr

*/#include #include #include void main()

/* handle several math errors caused by passing a negative argument

* returns the natural or base-10 logarithm of the absolute value

* of the argument and suppresses the usual error message.

*/int _matherr( struct _exception *except )

else if( strcmp( except->name, "log10" ) == 0 )

}else

}

輸出結果

special: using absolute value: log: _domain error

log( -2.0 ) = 6.931472e-001

special: using absolute value: log10: _domain error

log10( -5.0 ) = 6.989700e-001

normal: log( 0.0 ) = -1.#inf00e+000

作者資訊:

姓名:周雲才

C 捕獲異常 兜底函式

純自己記錄 在執行有可能出問題的 語句前,將函式新增進事件 取當前作用域 當前作用域出現未捕獲異常時,使用myhandler函式響應事件 new unhandledexceptioneventhandler currentdomain unhandledexception 當前作用域出現未捕獲異常時...

mysql異常捕獲 MySql中捕獲異常的方法

下面是程式設計之家 jb51.cc 通過網路收集整理的 片段。mysql中是否能有sqlserver的 error變數呢,或者如c 中的try catch語法呢。答案是肯定的,例項 如下 code drop procedure if exists sp call jobs create proced...

關於異常捕獲

你可以查一下你的sdk,裡面有很多的exception的定義,其基類其實都是system.exception一樣。但system.exception只提供了一些一般異常的處理。更多的需要專業的來處理。比如找不到檔案,你必須捕捉system.io.filenotfoundexception這個異常。在...