C++异常处理的一些基本知识
#include <iostream>
using namespace std;
int Devide(int x, int y)
{
if (y == 0)
{
throw(y);//第一步:设定可能发生的异常条件,throw(int/类/数组都是可以的)
}
return x/y;
}
void test01()
{
try
{
Devide(10, 0);//第二步:在throw的上层调用函数,使用try{Devide(10,0)}
}
catch (int e)//第三步:catch()那个throw(数据类型)出来的数据类型
cout << "除数为:" << e << endl;
}
}
int main(void)
{
test01();
return 0;
}
第一步:设定可能发生的异常条件,throw(int/类/数组都是可以的)
第二步:在throw的上层调用函数,使用try{Devide(10,0)}
第三步:catch(数据类型 数据名)那个throw(数据)出来的数据类型
栈解旋
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "对象创建" << endl;
}
~Person()
{
cout << "对象析构" << endl;
}
};
int Devide(int x, int y)
{
Person p1, p2;
if (y == 0)
{
throw(y);
}
return x/y;
}
void test01()
{
try
{
Devide(10, 0);
}
catch (int e)
{
cout << "除数为:" << e << endl;
}
}
int main(void)
{
test01();
return 0;
}
执行结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B0PvVg28-1591800620277)(C:\Users\19799\AppData\Roaming\Typora\typora-user-images\1591691260792.png)]
所以栈解旋的意思就是:在异常出现的函数体中,也就是在使用throw语句的函数题中,所有的在函数体中的局部遍量,也就是函数体中创建在存储在栈上面的变量会自动释放。
这就是栈解旋。
进阶,我们来使用一个继承来书写一个异常
// 标准异常库使用.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#pragma warning(disable:4996)
#include <iostream>
#include<stdexcept>
using namespace std;
class BaseMyException
{
public:
virtual void what() = 0;//纯虚函数
virtual ~BaseMyException() {}//这里不能写成纯虚函数,不然子类要完全重写父类的纯虚函数 返回值和函数名都必须相同
};
class TargetNull :public BaseMyException
{
public:
virtual void what()
{
cout << "targe is null" << endl;
}
~TargetNull()
{
cout << "TargetNull 析构调用" << endl;
}
};
class SourceNull :public BaseMyException
{
public:
virtual void what()
{
cout << "Source is null" << endl;
}
~SourceNull()
{
cout << "SourceNull 析构调用" << endl;
}
};
void Copy_String(char* target, char* source)
{
if (target == NULL)
{
//cout << "target is NULL"<< endl;
throw TargetNull();
}
if (source == NULL)
{
// cout << "source is NULL" << endl;
throw SourceNull();
}
//int len = strlen(source) + 1;
while (*source != '\0')
{
*target = *source;
target++;
source++;
}
}
using namespace std;
int main()
{
char * source = (char *)"hello";
char buf[256] = { 0 };
try
{
Copy_String(buf, source);
}
catch (BaseMyException& e)
{
e.what();
}
cout << buf << endl;
std::cout << "Hello World!\n";
}
ring(buf, source);
}
catch (BaseMyException& e)
{
e.what();
}
cout << buf << endl;
std::cout << “Hello World!\n”;
}
c++的标准异常库也是以类的形式给我们使用的,**我们一般是继承他的标准异常库,然后书写我们自己具体的异常类,然后catch(这里就可以统一写标准异常类),**因为我们自己的异常类都是继承与标准异常类,catch就可以统一写标准异常类,这样方便编程的规范性,