C++中内置了异常处理的语法元素try...catch...
--try语句处理正常代码逻辑
--catch语句处理异常情况
--try语句中的异常由对应的catch语句处理
try
{
double r = divide(1, 0);
}
catch(...)
{
cout << "Divide Exception..." << endl;
}
C++通过throw语句抛出异常,throw关键字后边跟的是一种"异常标志",可以是任何数据类型(包括自定义类)来代表异常。
【编程实验】C++异常使用
double divide (double e, bouble b)
{
const double delta = 0.00000000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
throw 0;//除0异常
}
return ret;
}
C++异常处理分析
--throw抛出的异常必须被catch处理。
--当前函数能够处理,程序继续往下执行。
--当前函数不能处理,沿着函数调用栈向上传播,如果整个函数调用栈中的函数都不能处理,则程序停止执行。
未被处理的异常会顺着函数调用栈向上传播,直到被处理为止,否则程序将停止执行。
function3抛出异常1,当function3不能处理这个异常的时候,异常1会继续沿着函数调用栈执行,直到被处理为止,如果最后没有被处理,程序停止执行。
【编程实验】异常沿函数调用栈传播
#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
const double delta = 0.000000000000001;
double ret = 0;
if( !((-delta < b) && (b < delta)) )
{
ret = a / b;
}
else
{
throw 0;//抛出异常,但是当前函数不能处理,沿着程序调用栈向上传播。
}
return ret;
}
int main(int argc, char *argv[])
{
try
{
double r = divide(1, 0);//这里抛出异常
cout << "r = " << r << endl;
}
catch(...)//这里catch(...)表示捕捉任何种类的异常
{
cout << "Divided by zero..." << endl;
}
return 0;
}
C++异常处理要点:
--同一个try语句可以跟上多个catch语句(想象一下,try语句块中可以抛出多种类型的异常,而下边跟了多个catch语句来捕捉,如果前些catch都没有捕捉到该异常,最后一个我们放大招catch(...),不管什么,都收了)
--catch语句可以定义具体处理的异常类型
--不同类型的异常由不同的catch语句负责处理
--try语句块中可以抛出任何类型的异常
--catch(...)用于处理所有类型的异常
--任何异常都只能被捕获(catch)一次
异常匹配处理规则:
catch(数据类型)用于异常,用法有点像函数参数,与函数参数不一样的是,编译器对catch中的类型不做任何类型推导,严格匹配,字符就是字符,整型就是整型。
【编程实验】C++中异常严格匹配
#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
try
{
throw 'c';//这里抛出char类型的异常
}
catch(int c)//这里捕获int类型的异常,不会对'c'做任何类型转换
{
cout << "catch(int c)" << endl;
}
catch(char c)//这里捕获char类型
{
cout << "catch(char c)" << endl;
}
catch(double c)
{
cout << "catch(double c)" << endl;
}
catch(...)
{
cout << "catch(...)" << endl;
}
}
void Demo2()
{
throw string("D.T.Software");//排除string类型异常
}
int main(int argc, char *argv[])
{
Demo1();
try
{
Demo2();//这里会抛出异常
}
catch(char* s)
{
cout << "catch(char *s)" << endl;//这里捕获字符数组异常
}
catch(const char* cs)//这里捕获const 字符数组异常
{
cout << "catch(const char *cs)" << endl;
}
catch(string ss)//这里捕获我们刚刚抛出的那种string类型的异常
{
cout << "catch(string ss)" << endl;
}
system("pause");
return 0;
}
VS2015执行结果:catch(char c)
catch(string ss)
小结:
--C++中直接支持异常语法概念
--try...catch...用于C++中的异常处理
--try语句处理正常执行的代码逻辑,catch语句用于处理异常逻辑
--同一个try语句可以跟上多个catch语句
--异常处理必须进行严格的类型匹配,编译器不做任何类型推导