基本异常处理
1.异常处理机制:暂缓问题处理,不在当前函数中处理,在它调用者中处理
2.任何东西都可以为异常,错误只是异常的一种
3.异常一旦被抛出,不做处理,如果引发异常,会调用默认abort终止程序
4.捕获和处理异常
(1)throw抛出异常
(2)try(检查,捕获)和catch(处理异常)一起出现,{}不可省略
(3)一个try可以对相应多个catch,只能执行一个匹配项
(4)不能存在两个相同的异常处理类型
(5)异常处理中char和int类型不会互相转换
(6)catch(...)处理任何异常类型
(7)throw()和noexcept(函数中不存在抛出异常)
#include <iostream>
using namespace std;
int division(int a,int b)
{
if (b == 0)
throw 0;
return a / b;
}
int main()
{
try
{
division(1 , 0);
}
catch (int)
{
cout << "除数不能为零" << endl;
}
return 0;
}
异常处理中的传参
#include <iostream>
#include <string>
using namespace std;
int division(int a,int b)
{
if (b == 0)
throw "除数不能为0";
if (b == 1)
throw "除数不能为1";
if (b == 2)
throw "除数不能为2";
return a / b;
}
class err
{
public:
err(const char* str="未知错位") :str(str){}
void print()
{
cout << str << endl;
}
protected:
string str;
};
void insertarr(int arr[], int* cur, int num, int max)
{
if (*cur >= max)
throw err("数组下标溢出");
arr[*cur] = num;
(*cur)++;
}
int main()
{
try
{
division(1 , 0);
}
catch (const char* str)
{
cout << str << endl;
}
try
{
int arr[3] = { 0, 0, 0 };
int cur = 0;
for (int i = 0; i < 4; i++)
{
insertarr(arr, &cur, i, 3);//数组下标溢出
}
}
catch (err str)
{
str.print();
}
return 0;
}
标注库的异常
自定义异常
1.自己写异常描述类
2.继承标准库中异常类
#include <exception>
#include <iostream>
using namespace std;
class myexception :public exception
{
public:
myexception(const char* str) :exception(str){}
};