异常的处理:任何东西都可以认为是有异常的,错误只是异常的一种
所谓异常处理机制 延缓当前问题的处理,不在当前的函数中处理,可以在调用它的函数中处理
注意点1:异常一旦被抛出,不做处理,如果引发异常,将会调用abort终止程序
捕获和处理异常:
throw 抛出异常,(可以理解为返回值,值是任何类型都可以,使我们处理异常一个参照)
try(检查,捕获)和catch(处理异常)
int main()
{
try
{
//此处为检查异常的代码
}
catch (类型) //根据类型进行处理异常问题
{
}
//一个try可以对应多个catch
try
{
//...
}
catch (...)//删减符,代表所有异常都捕获
catch (int) {
}
catch (double) {
}
catch (string) {
}
return 0;
}
不存在异常的描述:
throw () noexcept //新版描述关键字
该关键字用来声明在当前函数内不存在异常,如果在规则加强的情况下,在声明没有异常却抛出
异常后将编译失败,我认为该关键字的作用为增加代码的可读性,我告诉他人该代码中没有抛出一异常的d
#include<iostream>
#include<string>
using namespace std;
void MyPrintf() throw()//告知不存在异常
{
cout << "该函数内不应有异常概念" << endl;
}
void MyPrintf2() noexcept
{
cout << "该函数内不应有异常概念" << endl;
}
int main()
{
return 0;
}
异常处理中的传参
#include<iostream>
#include<string>
using namespace std;
class Error
{
public:Error(const char* str = "未知类型") :str(str) {};
protected:
string str;
};
int divisor(int a,int b)
{
if (b==0)
{
throw "除数不能为0"; //抛出异常
}
if (a == 0)
{
throw "被除数不能为0"; //我愿意抛出什么异常就抛出什么异常
}
return a / b;
}
int main()
{
try
{
divisor(1, 0);
}
catch (const char *str) //str类型解析为char*
{
cout << str << endl;
}
catch (int) //如果把上面的代码屏蔽掉,没找到合适的匹配项处理异常,程序将会调用abort结束
{
cout << 1 << endl;
}
return 0;
}
自定义类型描述异常
继承标准库中的类描述异常
#include <iostream>
#include <string>
using namespace std;
//自己写的异常描述类
class Error
{
public:
Error(const char* str = "未知错误") :str(str) {}
const char* what()const
{
return str.c_str();
}
protected:
string str;
};
void insertArray(int array[], int* curNum, int posData, int maxLength)
{
if (*curNum >= maxLength) //3>=3
{
throw Error("数组下标溢出!");
}
//0 1 2
array[*curNum] = posData; //array[3]=3
(*curNum)++;
}
void testOne()
{
try {
int array[3] = { 0,0,0 };
int curNum = 0;
for (int i = 0; i < 4; i++) {
insertArray(array, &curNum, i, 3);
}
}
catch (Error str)
{
cout << str.what() << endl;
}
}
class myException :public exception
{
public:
myException(string str) :exception(str.c_str()) {}
};
void insertArray(int a)
{
if (a >= 4)
throw myException("数组满了!");
cout << "插入成功" << endl;
}
void deleteArray(int a)
{
if (a <= 0)
throw myException("数组为空,无法删除");
cout << "删除成功" << endl;
}
void testTwo()
{
try
{
insertArray(1);
insertArray(4);
}
catch (myException& object) {
cout << object.what() << endl;
}
try {
deleteArray(1);
deleteArray(0);
}
catch (myException& object) {
cout << object.what() << endl;
}
}
int main()
{
testOne();
testTwo();
return 0;
}