1 基本的异常处理
异常处理机制:暂缓问题处理,不在当前函数中处理,在调用者中处理
任何东西都可为异常,错误只是异常的一种
异常一旦抛出,不做处理,引发异常时,调用abort终止程序
捕获与处理
throw抛出异常
try(检查,捕获)catch(处理异常) tyr和catch一起出现
删减符...任何类型的数据都捕获
2 异常处理中的传参
catch(int a)隐藏一个传参操作
想要处理抛出字符串的异常处理,注意string与const char*
#include <iostream>
#include <string>
using namespace std;
class Error
{
public:
Error(const char* str = "未知错误") :str(str) {}
const char* what()
{
cout << "异常处理" << endl;
}
protected:
string str;
};
int divisor(int a, int b)
{
if (b == 0)//b=0为异常,0不可为除数
throw 0;//抛出0
if (b == -1)
throw "原数加负号";
if (b == 1)
throw string("还是原数啊");//抛出字符串
return a / b;
}
void insertArray(int arry[], int* curNum, int posData, int maxLength)
{
if (*curNum >= maxLength)
throw Error("数组下标溢出");
arry[*curNum] = posData;
(*curNum)++;
}
void printerroe0()throw()
{
cout << "表示此函数不存在异常" << endl;
}
void printerror1()noexcept
{
cout << "新的描述表示不存在异常,加在函数之后" << endl;
}
int main()
{
try//一个try可以对应多个catch
{
divisor(8, 0);//正常需要检查是否存在异常的代码
//引发异常后try之后的代码不会执行,直接跳到catch中
}
catch(int)//要检测的函数的数据类型为int
{
cout << "除数不能为0" << endl;//根据输出数据类型决定如何处理
}
//catch只能执行一个匹配项
// catch (...)
// {
// //删减符,捕获任何类型的异常
// }//这里先把他注释掉,不然影响下面操作
catch (const char* str)
{
cout << str << endl;
}
catch (string str)
{
cout << str << endl;
}
try
{
int arry[3] = { 9,9,9 };
int curNum = 0;
for (int i = 0; i < 4; i++)
{
insertArray(arry, &curNum, i, 3);
}
}
catch (Error str)
{
cout << str.what() << endl;
}
return 0;
}
3 标准库中的异常
4 自定义异常
#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 arry[], int* curNum, int posData, int maxLength)
{
if (*curNum >= maxLength)
throw Error("数组下标溢出");
arry[*curNum] = posData;
(*curNum)++;
}
void test()
{
try
{
int arry[3] = { 9,9,9 };
int curNum = 0;
for (int i = 0; i < 4; i++)
{
insertArray(arry, &curNum, i, 3);
}
}
catch (Error str)
{
cout << str.what() << endl;
}
}
//继承标准库中的异常类
//重写what方法
class myexception :public exception
{
public:
myexception(string str) :exception(str.c_str()) {}
};
void inserArry(int a)
{
if (a == 4)
throw myexception("数组已满");
cout << "插入成功" << endl;
}
void inserArry(int a)
{
if (a == 0)
throw myexception("数组为空");
cout << "删除成功" << endl;
}
void test1()
{
try
{
inserArry(4);
inserArry(0);
}
catch (myexception& object)
{
cout << object.what() << endl;
}
}
int main()
{
test();
test1();
return 0;
}