1 基本异常处理
1.1 异常
任何东西都可以当做异常,错误(除数不能为0,数组溢出)只是其中一种。异常会中断程序,处理异常可以理解为错误提示。
1.2 异常处理机制
暂缓问题处理,不在当前函数中处理,在他的调用者或调用者的调用者里处理
异常一旦被抛出,不做处理,如果引发异常,会调用默认的absort终止程序(标准库自带的)。
1.3 异常的抛出 捕获与处理
1.3.1 抛出 throw
throw抛出异常,可理解为返回值, 任意类型的任意值都可,起标识作用。
int divisor(int a, int b)
{
//抛出了异常并未做处理,会调用默认的absort终止程序
if (b == 0)
throw 0; // b 不能为0, b若为0,让他抛出异常 throw 0; 这的值可以是任意值
if (b == 1)
throw 1; // 也可以把1 当做异常 进行抛出, 可以抛出多个异常 但只会处理一个
if (b == 2)
throw "抛出字符串类型异常";
if (b == 3)
throw 'c'; //抛出字符类型 可以是任意类型
//可抛出多个 但只能引发一个异常
return a / b;
}
void print(int a, int b)
{
divisor(a,b);
}
int main()
{
print(1,0);
return 0;
}
检查 捕获 try
处理异常 catch
try 与catch 必须一起出现 并且 他们的{}不可省略
一个try可以多应多个catch
catch 是根据抛出数据类型决定如何处理
与 if else if else 执行机制一样,只能执行一个匹配项
try
{
print(1,0); //一旦引发异常,就会跳到相应的catch处 不会再执行下面的语句
print(1,1);
}
catch(int)
{
cout << "除数不能为0" << endl;
}
//catch (int) //不能 同种类型的catch
//{
// cout << "除数不能为0" << endl;
//}
catch (char) //不存在类型互转 假如抛出 int类型0 引发absort
{
}
catch (string)
{
}
catch (...) //能捕获任意类型的异常
{
}
void print() throw()
{
cout << "当前函数不存在抛出异常操作" << endl;
//throw 0; 不可以
}
void printData() noexcept
{
cout << "新标准关键词:不存在抛出异常操作" << endl;
}
不存在抛出异常
两个关键字 throw noexcept
表明当前函数不存在抛出异常
2 异常处理中的传参
catch(int a) //隐藏了一个传参操作
想要处理字符串类型的传参,需要注意char *和const char * 转化,
也可抛出自定义类对象
#include<iostream>
using namespace std;
int divisor(int a, int b)
{
if (b == 0)
throw 0;
if (b==0)
{
throw string("通过构造方式抛出");
}
if (b == 3)
throw "抛出字符串类型"; //抛出字符类型 可以是任意类型
return a / b;
}
void print(int a, int b)
{
divisor(a, b);
}
int main()
{
try
{
print(1,0);
}
catch(const char str)
{
cout << str << endl;
}
catch (string str)
{
cout << str << endl;
}
return 0;
}
自定义异常类
class Error
{
public:
Error(const string 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)
throw Error("数组下标溢出");
array[*curNum] = posData;
(*curNum)++;
}
int main()
{
try
{
int arr[2] = {1,2};
int curNum = 0;
for (int i = 0; i < 3; i++)
{
insertArray(arr,&curNum,i,2);
}
}
catch (Error str)
{
cout << str.what() << endl;
}
return 0;
}
使用标准库做异常类
#include<iostream>
using namespace std;
class myExcetion:public exception
{
public:
myExcetion(string str) :exception(str.c_str())
{}
};
void insertArray(int a)
{
if (a == 4)
throw myExcetion("数组满了");
cout << "插入成功" << endl;
}
void delArray(int a)
{
if (a == 0)
throw myExcetion("数组为空,无法删除");
cout << "删除成功" << endl;
}
void testTwo()
{
try
{
insertArray(1);
delArray(0);
}
catch (myExcetion& object)
{
cout << object.what() << endl;
}
try
{
insertArray(4);
delArray(1);
}
catch (myExcetion& object)
{
cout << object.what() << endl;
}
}
int main()
{
testTwo();
return 0;
}