C++中的异常处理(上)
C++异常处理:
C++内置了异常处理的语法元素try…cath
try语句处理正常代码逻辑
catch语句处理异常情况
try语句中的异常由对应的catch语句处理
try
{
/* code */
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
C++中通过throw语句抛出异常信息
C++异常处理:
throw抛出的异常必须被catch处理
当前函数能够处理异常,程序继续往下执行
当前函数无法处理异常,则函数停止执行,并返回
编程实验:C++异常处理初探
#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(...)
{
cout << "Divided by zero..." << endl;
}
return 0;
}
用一个try语句可以跟上多个catch语句:
(1)catch语句可以定义具体处理的异常类型
(2)不同类型的异常由不同的catch语句负责处理
(3)try语句中可以抛出任何类型的异常
(4)catch(…)用于处理所有类型的异常,但是只能放在catch语句最后的地方
(5)任何异常都只能被捕获(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(...)
{
cout << "catch(...)" << endl;
}
}
void Demo2()
{
throw string("D.T.Software");
//throw "CK"; //抛出的异常类型是char const*
}
int main(int argc, char *argv[])
{
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;
}