上节课我们了解了C语言的异常处理方式,也了解了C中异常处理的许多的缺陷,下面我们来学习下C++中的异常处理。
看看C++中是怎么处理异常的。
一、C++中的异常处理
1、C++中内置了异常处理的语法元素try...catch...
- try语句处理正常代码逻辑
- catch语句处理异常情况
- try语句的异常由对应的catch语句处理
try
{
double r = divide(1,0);
cout << "r = " << r << endl;
}
catch(...)
{
cout << "Divide by zero..." << endl;
}
2、C++中通过throw抛出异常信息
double divide(double a,double b)
{
const double delta = 0.0000000001;
double ret = 0;
if(!((-delta < b)&&(b < delta)))
{
ret = a/b;
}
else
{
throw 0;
}
return ret;
}
3、C++异常处理分析
- throw抛出的异常必须被catch处理
- 当前函数如果能够处理异常,程序继续往下执行
- 当前函数无法处理异常,则函数停止执行,并返回
示例:C++异常处理初探
#include <iostream>
#include <string>
using namespace std;
double divide(double a,double b)
{
const double delta = 0.0000000001;
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 = " << r << endl;
}
catch(...)
{
cout << "Divide by zero..." << endl;
}
return 0;
}
打印结果
4、同一个try语句可以跟上多个catch语句
- catch语句可以定义具体处理的异常类型
- 不同类型的异常有不同的catch语句负责处理
- try语句可以抛出任何类型的异常
- catch(...)语句用于处理所有类型的异常
- 任何类型异常都只被catch语句捕获一次
- 异常处理匹配时,不进行任何的类型转换
示例:异常类型匹配
#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
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(int c)
{
cout << "catch(int c)" << endl;
}
catch(...)//只能在所有catch语句的后面,他可以处理所有类型的异常。
{
cout << "catch(...)" << endl;
}
}
void Demo2()
{
throw string("D.T.Software");
}
int main()
{
Demo1();
try
{
Demo2();
}
catch(char* s)
{
cout << "catch(char* s)" << endl;
}
catch(const char* cs)
{
cout << "catch(const char* cs)" << endl;
}
catch(string ss)
{
cout << "catch(string ss)" << endl;
}
return 0;
}
打印结果
小结:
- C++中直接支持异常处理的概念
- try...catch...是C++中异常处理的专用语句
- try处理正常语句逻辑,catch语句处理异常情况
- 同一个try语句可以跟上多个catch语句
- 异常处理必须严格匹配,不进行任何的类型转换