一般的异常处理
// 一般的异常
int func01(int _x, int _y)
{
if (_y == 0)
throw "除数=0";
return _x / _y;
}
// int func(int x, int y) throw(int, char, char *); //可以抛出int,char char*类型 若抛出float则在try{}模块检测不到
// int func(int x, int y) throw(); //不会抛出异常
// int func(int x, int y) //可以抛出任意类型的异常
void text01()
{
int x = 100;
try
{
// 可能会出现异常的语句
x = func01(10, 0);
}
// 接受const char*类型的异常
catch (const char *_str_error)
{
cout << _str_error << endl;
}
// 这里输出的仍旧是x初始化的数值100,因为func函数出现异常并没有执行异常下面的语句
cout << "x = " << x << endl;
}
栈解旋
// 栈解旋
class Text
{
public:
Text()
{
cout << "构造函数的调用" << endl;
}
~Text()
{
cout << "析构函数的调用" << endl;
}
};
void func02()
{
Text t1;
throw 1;
// 析构函数的发生是在异常处理之前执行
Text t2;
}
void text02()
{
try
{
func02();
}
catch (int errorCode)
{
cout << "errorCode:" << errorCode << endl;
}
cout << "text02函数执行完成" << endl;
}
完整代码
#include <iostream>
using namespace std;
// 一般的异常
int func01(int _x, int _y)
{
if (_y == 0)
throw "除数=0";
return _x / _y;
}
// int func(int x, int y) throw(int, char, char *); //可以抛出int,char char*类型 若抛出float则在try{}模块检测不到
// int func(int x, int y) throw(); //不会抛出异常
// int func(int x, int y) //可以抛出任意类型的异常
void text01()
{
int x = 100;
try
{
// 可能会出现异常的语句
x = func01(10, 0);
}
// 接受const char*类型的异常
catch (const char *_str_error)
{
cout << _str_error << endl;
}
// 这里输出的仍旧是x初始化的数值100,因为func函数出现异常并没有执行异常下面的语句
cout << "x = " << x << endl;
}
// 栈解旋
class Text
{
public:
Text()
{
cout << "构造函数的调用" << endl;
}
~Text()
{
cout << "析构函数的调用" << endl;
}
};
void func02()
{
Text t1;
throw 1;
// 析构函数的发生是在异常处理之前执行
Text t2;
}
void text02()
{
try
{
func02();
}
catch (int errorCode)
{
cout << "errorCode:" << errorCode << endl;
}
cout << "text02函数执行完成" << endl;
}
int main(int argc, char **argv)
{
text01();
text02();
return 0;
}
运行结果
总结: 类遇到异常处理的时候,析构函数的发生是在异常处理之前执行,异常后面的代码仍旧不会执行