目录
基本的异常处理
- 异常处理机制:暂缓问题处理,不在当前函数中处理,在他的调用者中处理
- 什么是异常:任何东西都可以人为是异常,错误只是异常的一种
- 异常一旦备抛出,不做处理,如果引发异常,会调用abort函数终止程序
- 捕获和处理异常:
- throw抛出异常(可以理解为返回值,值是任何类型都可以,这是我们处理异常的一个参照)
- try(检查,捕获)和catch(异常处理)
try与catch必须是同时出现,并且它们的{}不能省略
catch和if else if的处理机制是一样的,只能执行一个匹配项
try
{
//正常需要检查是否出现异常代码
}
catch(类型)//理解为switch 语句中的case
{
//根据抛出类型决定怎么处理
}
//一个try可以对应多个catch
try
{
}
catch(int){}
catch(double){}
catch(string){}
#include<iostream>
using namespace std;
int Mod(int a,int b){
if (b == 0)throw 0;//抛出异常
return a / b;
}
int main(){
try
{
cout << Mod(1, 0);
}
catch (int){
cout << "除数不能为零!" << endl;
}
/*catch (...)//(...)捕获所有类型的异常
{
cout << "除数不能为零!" << endl;
}*/
while (1);
return 0;
}
不存在异常的处理
- throw()
- noexcept
void print()throw(){cout<<"当前函数不存在抛出异常操作!"<<endl;}
void func()noexcept{cout<<"新标准:不存在异常操作!"<<endl;}
//throw 0;,编译不过,一旦说明没有异常操作,就无法抛出
异常处理中的传参
- catch(int a)//隐藏一个传参操作
- 想要处理字符串类型的异常,注意string跟const char* 的区别
- 也可以抛出自己类的对象
#include<iostream>
using namespace std;
class error{
public:
error(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 a[3] = { 0, 1, 1 };
int curNum = 0;
for (int i = 0; i < 4; i++)
insertArray(a, &curNum, i, 3);
}
catch (error str){
cout << str.what() << endl;
}
while (1);
return 0;
}
自定义异常类
#include<iostream>
#include<exception>
using namespace std;
class myException:public exception//继承标准库中的异常类,通过重写what函数
{
public:
myException(string str) :exception(str.c_str()){}
protected:
};
void insertArray(int a){
if (a == 4)throw myException("数组满了!");
cout << "插入成功!" << endl;
}
void insertArray1(int a=0){
if (a== 0)throw myException("数组为空,无法删除!");
cout << "删除成功!" << endl;
}
void testOne(){
try{
insertArray(0);
insertArray1(0);
}
catch (myException& object){
cout << object.what() << endl;
}
}
int main(){
testOne();
while (1);
return 0;
}
标准库里的异常
#include<iostream>
#include<exception>
using namespace std;
class Exception{
public:
Exception(const char* str = "UNKNOW") :ptr(const_cast<char*>(str)){}
virtual const char*what()const{ return ptr; }
protected:
char* ptr;
};
class Bad_alloc:public Exception
{public:
Bad_alloc(const char* message = "bad Exception") :Exception(message){}
protected:
};
class Run_time :public Exception {
public:
Run_time(const char* message = "run time error") :Exception(message){}
protected:
};
int main(){
try{
while (1){
int* p = new int[1024*1024];
}
}
catch (Bad_alloc&object){ cout << object.what() << endl; }
while (1);
return 0;
}