1. C++異常處理
-
C++內(nèi)置了異常處理的語法元素
try...catch...
(1)try
語句處理正常代碼邏輯
(2)catch
語句處理異常情況
(3)try
語句中的異常有對應(yīng)的catch
語句處理
-
C++通過
throw
語句拋出異常信息
-
C++異常處理分析
throw
拋出的異常必須被catch
處理
(1) 當(dāng)前函數(shù)能夠處理異常岩调,程序繼續(xù)往下執(zhí)行
(2) 當(dāng)前函數(shù)無法處理異常查近,則函數(shù)停止執(zhí)行娃循,并返回
(3) 未被處理的異常會(huì)順著函數(shù)調(diào)用棧向上傳播挺身,直到被處理為止,否則程序?qū)⑼V箞?zhí)行蹭劈。
編程說明:C++異常處理初探
#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
const double delta = 0.00000000000001;
double ret = 0;
if ( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
throw 0;
}
return ret;
}
int main()
{
try
{
double r = divide(1, 0);
cout << r << endl;
}
catch(...)
{
cout << "Divided by zero ... " << endl;
}
return 0;
}
輸出結(jié)果:
Divided by zero ...
2. 深入理解try...catch...
- 同一個(gè)
try
語句可以跟上多個(gè)catch
語句 -
catch
語句可以定義具體處理的異常類型 -
不同類型的異常由不同的
catch
語句負(fù)責(zé)處理 -
try
語句中可以拋出任何類型的異常 -
catch(...)
用于處理所有類型的異常 - 任何異常都只能被捕獲(catch)一次
3. 異常處理的匹配規(guī)則
- 異常拋出后厌处,至上而下嚴(yán)格匹配每一個(gè)catch語句處理的類型侦另。異常處理匹配時(shí)特纤,不進(jìn)行任何的類型轉(zhuǎn)換军俊。
編程說明:異常類型匹配
#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
try
{
throw 1;
}
catch(char c)
{
cout << "catch(char c)" << endl;
}
catch(short s)
{
cout << "catch(short s)" << endl;
}
catch(double d)
{
cout << "catch(double d)" << endl;
}
catch(int i)
{
cout << "catch(int i)" << endl;
}
catch(...)
{
cout << "catch(...)" << endl;
}
}
void Demo2()
{
throw "abcd";
}
int main()
{
Demo1();
try
{
Demo2();
}
catch(const char* s)
{
cout << "catch(const char* s)" << endl;
}
catch(string ss)
{
cout << "catch(string ss)" << endl;
}
return 0;
}
輸出結(jié)果
catch(int i)
catch(const char* s)
4. 小結(jié)
- C++中直接支持異常處理的概念
-
try...catch...
是C++中異常處理的專用語句 -
try
語句處理正常代碼邏輯,catch
語句處理異常情況 - 同一個(gè)
try
語句可以跟上多個(gè)catch
語句 - 異常處理必須嚴(yán)格匹配捧存,不進(jìn)行任何的類型轉(zhuǎn)換