異常是指程序在運(yùn)行過(guò)程中產(chǎn)生可預(yù)料的執(zhí)行分支。如除0操作,數(shù)組訪問(wèn)越界、要打開的文件不存在。
Bug是指程序中的錯(cuò)誤,是不被預(yù)期的運(yùn)行方式。如野指針、堆空間使用結(jié)束未釋放。
C語(yǔ)言中處理異常的方式一般是使用if....else...分支語(yǔ)句。
創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站制作、做網(wǎng)站、江孜網(wǎng)絡(luò)推廣、微信小程序、江孜網(wǎng)絡(luò)營(yíng)銷、江孜企業(yè)策劃、江孜品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供江孜建站搭建服務(wù),24小時(shí)服務(wù)熱線:18982081108,官方網(wǎng)址:www.rwnh.cn
double divide(double a, double b)
{
const double delta = 0.000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
cout << "a is devieded by zero" <<endl;
}
return ret;
}
C語(yǔ)言通過(guò)setjmp和longjmp對(duì)異常處理進(jìn)行優(yōu)化。int setjmp(jmp_buf env);
將上下文保存到j(luò)mp_buf結(jié)構(gòu)體中void longjmp(jmp_buf env, int value);
從jmp_buf結(jié)構(gòu)體中恢復(fù)setjmp保存的上下文,最終從setjmp函數(shù)調(diào)用點(diǎn)返回,返回值為value。
#include <iostream>
#include <csetjmp>
using namespace std;
static jmp_buf env;
double divide(double a, double b)
{
const double delta = 0.000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
longjmp(env, 1);
}
return ret;
}
int main(int argc, char *argv[])
{
if( setjmp(env) == 0 )
{
double r = divide(1, 1);
cout << "r = " << r << endl;
}
else
{
cout << "Divided by zero..." << endl;
}
return 0;
}
C++語(yǔ)言中內(nèi)置了異常處理的語(yǔ)法,try.....catch......。
try語(yǔ)句塊用來(lái)處理正常代碼邏輯,catch語(yǔ)句塊用來(lái)處理異常處理情況,throw拋出異常。在try語(yǔ)句塊拋出的異常在相應(yīng)的catch語(yǔ)句塊捕獲處理。
同一個(gè)try語(yǔ)句塊可以對(duì)應(yīng)多個(gè)catch語(yǔ)句塊,catch語(yǔ)句塊可以定義具體處理的異常類型,不同的類型的異常由不同的catch語(yǔ)句塊處理,try語(yǔ)句塊可以拋出任何類型的異常,catch(...)用于處理所有類型的異常,任何異常都只能被捕獲一次。
throw拋出的異常必須被catch處理,如果當(dāng)前函數(shù)能夠處理異常,繼續(xù)執(zhí)行;如果當(dāng)前函數(shù)不能處理異常,函數(shù)停止執(zhí)行并返回。未被處理的異常會(huì)順著函數(shù)調(diào)用棧向上傳遞,直到被處理為止,否則程序?qū)⑼V箞?zhí)行。
異常處理的匹配:
A、異常拋出后從上到下嚴(yán)格匹配每個(gè)catch語(yǔ)句塊處理的類型,不能進(jìn)行任何類型轉(zhuǎn)換。
B、catch(...)語(yǔ)句塊只能放到catch語(yǔ)句塊分支的最后位置。
異常處理的使用實(shí)例:
try
{
throw 'c';
}
catch(char c)
{
cout << "catch(char c)" << endl;
}
catch(short c)
{
cout << "catch(short c)" << endl;
}
catch(double c)
{
cout << "catch(double c)" << endl;
}
catch(...)
{
cout << "catch(...)" << endl;
}
catch語(yǔ)句塊捕獲的異常重新解釋后可以拋出異常,拋出的異常在外層的try...catch中捕獲。
try
{
try
{
throw 'c';
}
catch(int i)
{
cout << "Inner: catch(int i)" << endl;
throw i;
}
catch(...)
{
cout << "Inner: catch(...)" << endl;
throw;
}
}
catch(...)
{
cout << "Outer: catch(...)" << endl;
}
通常在catch語(yǔ)句塊中捕獲的異常重新解釋后可以再次拋出異常,工程實(shí)踐中通常用于統(tǒng)一異常類型,如通過(guò)捕獲第三方庫(kù)函數(shù)中拋出的異常,重新解釋后拋出統(tǒng)一的異常處理信息。
異常的類型可以是自定義類型,自定義類型的異常匹配依舊是自上而下嚴(yán)格匹配,但由于賦值兼容性原則在異常匹配中適用,所以匹配子類異常的catch語(yǔ)句塊放在catch分支的上部,匹配父類異常的catch語(yǔ)句塊放在catch分支的下部。
#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int i):code(i)
{
}
private:
int code;
};
class Child : public Parent
{
public:
Child(int i):Parent(i),code(i)
{
}
private:
int code;
};
int main(int argc, char *argv[])
{
try
{
Child child(1);
throw child;
}
catch(const Child& e)
{
cout << "catch(const Child& e)" << endl;
}
catch(const Parent& e)
{
cout << "catch(const Parent& e)" << endl;
}
return 0;
}
STL提供了實(shí)用的異常處理類,STL中的異常都是從exception類繼承而來(lái),exception類只要有兩個(gè)分支,logic_error和runtime_error。logic_error用于處理程序中可避免邏輯錯(cuò)誤,runtime_error用于處理程序中無(wú)法處理的惡性錯(cuò)誤。
#include <iostream>
#include <stdexcept>
using namespace std;
int main(int argc, char *argv[])
{
int array[5] = {0};
for(int i = 0; i < 5; i++)
{
array[i] = i;
}
try
{
for(int i = 0; i < 10; i++)
{
if(i >= 5)
{
throw out_of_range("out of range");
}
else
{
cout << array[i] <<endl;
}
}
}
catch(const out_of_range& e)
{
cout << e.what() << endl;
}
return 0;
}
try...catch語(yǔ)句用于分隔正常功能代碼與異常處理代碼。try...catch語(yǔ)句也可以將函數(shù)體分隔為兩部分。
函數(shù)聲明和定義時(shí)可以直接指定可能拋出的異常類型,異常聲明作為函數(shù)的一部分可以提高代碼可讀性。
函數(shù)異常聲明是一種與編譯器之間的契約,函數(shù)聲明異常后就只能拋出聲明的異常。如果拋出其它異常將會(huì)導(dǎo)致程序運(yùn)行終止。也可以通過(guò)函數(shù)異常聲明定義無(wú)異常函數(shù)。
#include <iostream>
using namespace std;
//聲明拋出的異常類型為int
void func(int i, int j)throw(int)
{
if(0 < j && j < 10)
{
}
else
{
throw 0;
}
}
void test(int i)try
{
func(i,i);
}
catch(int i)
{
cout << "catch(int i): " << i << endl;
}
catch(...)
{
cout << "Exception:" << endl;
}
int main(int argc, char *argv[])
{
test(10);
test(1);
return 0;
}
上述代碼中,func函數(shù)聲明了拋出的異常類型為int,因此func函數(shù)只能拋出int類型異常,如果拋出其它類型異常將導(dǎo)致程序運(yùn)行終止。即使test函數(shù)可以對(duì)拋出的其它類型異常進(jìn)行捕獲,程序也會(huì)運(yùn)行終止。
如果函數(shù)內(nèi)部可能會(huì)拋出多種類型的異常,需要在函數(shù)聲明異常時(shí)指定聲明的異常類型,代碼如下:
#include <iostream>
#include <string>
using namespace std;
//聲明拋出的異常類型為int,char,string
void func(int i, int j)throw(int,char,string)
{
if(0 < j && j < 10)
{
throw j;
}
if(10 < j && j < 100)
{
throw 'A';
}
else
{
throw string("string exception.");
}
}
void test(int i)try
{
func(i,i);
}
catch(int i)
{
cout << "catch(int i): " << i << endl;
}
catch(char c)
{
cout << "Exception:" << c << endl;
}
catch(string s)
{
cout << s << endl;
}
catch(...)
{
cout << "Exception:" << endl;
}
int main(int argc, char *argv[])
{
test(115);//string exception.
test(1);//catch(int i): 1
test(20);//Exception:A
return 0;
}
上述代碼中,func函數(shù)可以拋出多種類型的異常,test函數(shù)會(huì)捕獲func函數(shù)拋出的多種異常類型。
如果異常沒(méi)有被處理,terminate函數(shù)會(huì)被自動(dòng)調(diào)用。terminate函數(shù)是整個(gè)程序釋放系統(tǒng)資源的最后機(jī)會(huì)。默認(rèn)情況下,terminate函數(shù)調(diào)用abort庫(kù)函數(shù)終止程序。abort函數(shù)使得程序執(zhí)行異常而立即退出。
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test()" << endl;
}
~Test()
{
cout << "~Test()" << endl;
}
};
int main(int argc, char *argv[])
{
static Test test;
throw 1;
return 0;
}
上述代碼運(yùn)行結(jié)果如下:
C++支持使用自定義的terminate函數(shù)實(shí)現(xiàn)替換默認(rèn)的terminate函數(shù)實(shí)現(xiàn)。
自定義terminate函數(shù)的實(shí)現(xiàn)規(guī)則如下:
A、自定義一個(gè)無(wú)返回值、無(wú)參數(shù)的函數(shù)
B、不能拋出任何異常
C、必須以某種方式結(jié)束當(dāng)前程序
通過(guò)調(diào)用set_terminate函數(shù)可以設(shè)置自定義的terminate結(jié)束函數(shù),其用法如下:
A、參數(shù)類型為void (*)()
B、返回值為默認(rèn)的terminate函數(shù)入口地址
#include <iostream>
#include <cstdlib>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test()" << endl;
}
~Test()
{
cout << "~Test()" << endl;
}
};
void terminate_test()
{
cout << "void terminate_test()" << endl;
exit(1);
}
int main(int argc, char *argv[])
{
set_terminate(terminate_test);
static Test test;
throw 1;
return 0;
}
// output:
// Test()
// void terminate_test()
// ~Test()
上述代碼在最終terminate_test結(jié)束函數(shù)中調(diào)用了exit(1),exit函數(shù)會(huì)確保程序中全局、靜態(tài)數(shù)據(jù)區(qū)的對(duì)象被正確銷毀。如果使用abort函數(shù)替換exit函數(shù),程序運(yùn)行結(jié)果如下:
析構(gòu)函數(shù)中拋出異??赡軙?huì)導(dǎo)致最終結(jié)束函數(shù)terminate函數(shù)會(huì)被重復(fù)調(diào)用。
C++語(yǔ)言提供用于聲明函數(shù)拋出異常的語(yǔ)法聲明。異常聲明作為函數(shù)聲明的修飾符,位于函數(shù)參數(shù)表的后面。函數(shù)異常聲明的示例如下:
//可能拋出任何異常
void func1();
//只能拋出的異常類型:char,int
void func2() throw(char, int);
//不拋出任何異常
void func3() throw();
函數(shù)異常聲明的意義如下:
A、提示函數(shù)調(diào)用者必須做好異常處理的準(zhǔn)備
B、提示函數(shù)的維護(hù)者不要拋出其它異常
C、函數(shù)異常規(guī)格說(shuō)明是函數(shù)接口的一部分
如果函數(shù)拋出的異常類型不在函數(shù)異常聲明中,全局unexpected()函數(shù)會(huì)被調(diào)用。默認(rèn)的unexpected()函數(shù)會(huì)調(diào)用全局的terminate函數(shù),可以自定義函數(shù)替換默認(rèn)的unexpected()函數(shù)實(shí)現(xiàn)。
自定義的unexpected()函數(shù)的實(shí)現(xiàn)規(guī)則如下:
A、自定義一個(gè)無(wú)返回值、無(wú)參數(shù)的函數(shù)
B、能夠再次拋出異常,當(dāng)異常符合觸發(fā)函數(shù)的異常規(guī)格說(shuō)明時(shí),恢復(fù)程序執(zhí)行。否則,調(diào)用全局terminate函數(shù)結(jié)束程序。
通過(guò)調(diào)用set_unexpected函數(shù)可以設(shè)置自定義的unexpected()函數(shù),用法如下:
A、參數(shù)類型為void (*)()
B、返回值為默認(rèn)的unexpected()函數(shù)入口地址。
#include <iostream>
#include <cstdlib>
using namespace std;
void func() throw(int)
{
cout << "void func()throw(int)" << endl;
throw 'A';
}
void unexpected_test()
{
cout << "void unexpected_test()" << endl;
throw 1;
}
int main(int argc, char *argv[])
{
set_unexpected(unexpected_test);
try
{
func();
}
catch(int)
{
cout << "catch(int)" << endl;
}
catch(char)
{
cout << "catch(char)" << endl;
}
return 0;
}
// output:
// void func()throw(int)
// void unexpected_test()
// catch(int)
C++編譯器不一定對(duì)C++語(yǔ)言中函數(shù)異常規(guī)格說(shuō)明進(jìn)行支持。VC++編譯器不支持,G++編譯器支持。
C語(yǔ)言中,malloc函數(shù)申請(qǐng)內(nèi)存失敗時(shí)返回NULL值。
C++語(yǔ)言中,對(duì)于早期的C++編譯器,new關(guān)鍵字申請(qǐng)內(nèi)存失敗時(shí),返回NULL值;對(duì)于現(xiàn)代C++編譯器,new關(guān)鍵字申請(qǐng)內(nèi)存失敗時(shí),拋出std::bad_alloc異常。
C++語(yǔ)言規(guī)范中,new關(guān)鍵字的標(biāo)準(zhǔn)行為如下:
A、new在內(nèi)存分配時(shí),如果空間不足,會(huì)調(diào)用全局的new_handler函數(shù),new_handler函數(shù)中拋出std::bad_alloc異常;如果成功,會(huì)在分配的空間調(diào)用構(gòu)造函數(shù)創(chuàng)建對(duì)象,并返回對(duì)象的地址。
B、可以自定義new_handler函數(shù),處理默認(rèn)new內(nèi)存分配失敗的情況。
#include <iostream>
#include <cstdlib>
using namespace std;
void new_handler_test()
{
cout << "void new_handler_test()" << endl;
cout << "No enough memory" << endl;
exit(1);
}
int main(int argc, char *argv[])
{
set_new_handler(new_handler_test);
int* p = new(std::nothrow) int[10000000000];
return 0;
}
// output:
// void new_handler_test()
// No enough memory
上述代碼中,自定義new_handler函數(shù),拋出異常時(shí)會(huì)調(diào)用。
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
void new_handler_test()
{
cout << "void new_handler_test()" << endl;
cout << "No enough memory" << endl;
exit(1);
}
int main(int argc, char *argv[])
{
new_handler func = set_new_handler(new_handler_test);
cout << "func = " << func << endl;
if(func)
{
try
{
func();
}
catch(const bad_alloc& e)
{
cout << e.what() << endl;
}
}
return 0;
}
// func = 0
上述代碼是在G++編譯器、VC++編譯器下編譯執(zhí)行后打印的結(jié)果,表明G++編譯器、VC++編譯器沒(méi)有設(shè)置默認(rèn)的new_handler函數(shù)。如果C++編譯器(如BCC編譯器)設(shè)置有默認(rèn)的new_handler函數(shù),func函數(shù)執(zhí)行時(shí)將會(huì)拋出bad_alloc異常,被捕獲后打印出bad_alloc異常的相關(guān)信息。
不同的C++編譯器,new關(guān)鍵字申請(qǐng)動(dòng)態(tài)內(nèi)存失敗時(shí)表現(xiàn)不同。
工程實(shí)踐中,為了在不同C++編譯器間統(tǒng)一new關(guān)鍵字的行為,提高代碼的可移植性,解決方案如下:
A、重新定義全局的new/delete實(shí)現(xiàn),不拋出任何異常;自定義new_handler函數(shù),不拋出任何異常(不推薦)。
B、在類內(nèi)重載new/delete操作符,不拋出任何異常。
C、單次動(dòng)態(tài)內(nèi)存分配時(shí)使用nothrow參數(shù),指明new不拋出異常。
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class Test
{
int m_data;
public:
Test()
{
cout << "Test()" << endl;
m_data = 0;//異常
}
~Test()
{
cout << "~Test()" << endl;
}
void* operator new (unsigned int size)
{
cout << "operator new: " << size << endl;
// return malloc(size);
return NULL;
}
void operator delete (void* p)
{
cout << "operator delete: " << p << endl;
free(p);
}
void* operator new[] (unsigned int size)
{
cout << "operator new[]: " << size << endl;
// return malloc(size);
return NULL;
}
void operator delete[] (void* p)
{
cout << "operator delete[]: " << p << endl;
free(p);
}
};
int main(int argc, char *argv[])
{
Test* p = new Test();
cout << p << endl;
delete p;
return 0;
}
// output:
// operator new: 4
// Test()
// 異常
上述代碼在執(zhí)行new操作符函數(shù)后會(huì)調(diào)用Test構(gòu)造函數(shù),并在初始化m_data成員變量時(shí)拋出異常。為了確保不同C++編譯器在調(diào)用new關(guān)鍵字時(shí)具有相同的行為,需要在new失敗時(shí)不拋出異常,因此需要在new操作符增加函數(shù)的異常聲明。
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class Test
{
int m_data;
public:
Test()
{
cout << "Test()" << endl;
m_data = 0;//異常
}
~Test()
{
cout << "~Test()" << endl;
}
void* operator new (unsigned int size) throw()
{
cout << "operator new: " << size << endl;
// return malloc(size);
return NULL;
}
void operator delete (void* p)
{
cout << "operator delete: " << p << endl;
free(p);
}
void* operator new[] (unsigned int size) throw()
{
cout << "operator new[]: " << size << endl;
// return malloc(size);
return NULL;
}
void operator delete[] (void* p)
{
cout << "operator delete[]: " << p << endl;
free(p);
}
};
int main(int argc, char *argv[])
{
Test* p = new Test();
cout << p << endl;
delete p;
p = new Test[5];
cout << p << endl;
delete [] p;
return 0;
}
// output:
// operator new: 4
// 0
// operator new[]: 24
// 0
上述代碼對(duì)Test類的new和delete關(guān)鍵字進(jìn)行了重載,統(tǒng)一了new失敗時(shí)的行為。
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//不拋出異常
int* p = new(nothrow) int[1000000000];
cout << "p = " << p << endl;
delete [] p;
int array[2] = {0};
struct Test
{
int x;
int y;
};
//在??臻g創(chuàng)建對(duì)象
Test* pTest = new(array) Test();
pTest->x = 100;
pTest->y = 200;
cout << array[0] << endl;
cout << array[1] << endl;
//顯示析構(gòu)
pTest->~Test();
return 0;
}
// output:
// p = 0
// 100
// 200
上述代碼中使用nothrow關(guān)鍵字對(duì)象new進(jìn)行限制,確保new創(chuàng)建對(duì)象失敗時(shí)不會(huì)拋出異常。new關(guān)鍵字也可以指定創(chuàng)建對(duì)象的地址空間,比如??臻g。
不是所有的C++編譯器都遵循C++標(biāo)準(zhǔn)規(guī)范,C++編譯器可能重新定義new關(guān)鍵字的實(shí)現(xiàn),并在實(shí)現(xiàn)中拋出bad_alloc異常。VC++編譯器對(duì)new關(guān)鍵字進(jìn)行了重定義,new關(guān)鍵字在new.cpp文件中進(jìn)行了實(shí)現(xiàn)。
#ifdef _SYSCRT
#include <cruntime.h>
#include <crtdbg.h>
#include <malloc.h>
#include <new.h>
#include <stdlib.h>
#include <winheap.h>
#include <rtcsup.h>
#include <internal.h>
void * operator new( size_t cb )
{
void *res;
for (;;) {
// allocate memory block
res = _heap_alloc(cb);
// if successful allocation, return pointer to memory
if (res)
break;
// call installed new handler
if (!_callnewh(cb))
break;
// new handler was successful -- try to allocate again
}
RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0));
return res;
}
#else /* _SYSCRT */
#include <cstdlib>
#include <new>
_C_LIB_DECL
int __cdecl _callnewh(size_t size) _THROW1(_STD bad_alloc);
_END_C_LIB_DECL
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{ // try to allocate size bytes
void *p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{ // report no memory
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
/*
* Copyright (c) 1992-2002 by P.J. Plauger. ALL RIGHTS RESERVED.
* Consult your license regarding permissions and restrictions.
V3.13:0009 */
#endif /* _SYSCRT */
上述代碼顯示,在new失敗時(shí)默認(rèn)拋出bad_alloc異常。
標(biāo)題名稱:C++語(yǔ)言學(xué)習(xí)(十八)——異常處理
網(wǎng)站鏈接:http://www.rwnh.cn/article34/jgpose.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、響應(yīng)式網(wǎng)站、App設(shè)計(jì)、電子商務(wù)、ChatGPT、虛擬主機(jī)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)