問(wèn)題描述
try {
int* p = 0;
*p = 1;
} catch (...) {
cout << "null pointer." << endl;
}
我試圖捕捉這樣的異常,但它不起作用,有什么幫助嗎?
I tried to catch the exception like this but it doesn't work,any help?
推薦答案
C++ 中沒(méi)有空指針異常"這樣的東西.您可以捕獲的唯一異常是 throw
表達(dá)式顯式拋出的異常(另外,正如 Pavel 所指出的,一些標(biāo)準(zhǔn) C++ 異常由標(biāo)準(zhǔn) operator new
、dynamic_cast
等).C++ 中沒(méi)有其他例外.取消引用空指針、除以零等不會(huì)在 C++ 中產(chǎn)生異常,它會(huì)產(chǎn)生未定義行為.如果您希望在這種情況下拋出異常,您有責(zé)任手動(dòng)檢測(cè)這些條件并明確地執(zhí)行 throw
.這就是它在 C++ 中的工作方式.
There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw
expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new
, dynamic_cast
etc). There are no other exceptions in C++. Dereferencing null pointers, division by zero etc. does not generate exceptions in C++, it produces undefined behavior. If you want exceptions thrown in cases like that it is your own responsibility to manually detect these conditions and do throw
explicitly. That's how it works in C++.
您似乎正在尋找的其他任何東西都與 C++ 語(yǔ)言無(wú)關(guān),而是特定實(shí)現(xiàn)的功能.例如,在 Visual C++ 中,系統(tǒng)/硬件異常可以轉(zhuǎn)換"為 C++ 異常,但這種非標(biāo)準(zhǔn)功能是有代價(jià)的,通常不值得付出代價(jià).
Whatever else you seem to be looking for has noting to do with C++ language, but rather a feature of particular implementation. In Visual C++, for example, system/hardware exceptions can be "converted" into C++ exceptions, but there's a price attached to this non-standard functionality, which is not normally worth paying.
這篇關(guān)于如何捕捉空指針異常?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!