
正文
C++异常处理(一)----基本语法
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
- 实验环境 win7 下的vs2017,基本原则:throw抛出的数据类型,和cathc语句的数据类型要一致
- 异常的引发和异常的处理可以分布在不同函数中,所以c++的异常是跨栈的
- 异常是由“地地道道“的错误所引发
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string.h>
using namespace std; void testerror(int x,int y)
{ if (y==)
{
throw x;
}
cout << "计算结果:"<<x/y<< endl;
} void main()
{
try
{
testerror(,);
}
catch (int x)
{
cout << x << "不能被0整除" << endl;
}
catch (...)
{
cout << "无言的结局" << endl;
}
system("pause");
}
- 下面的例子揭示了throw语句的强大,无论多少层都会抛出错误
void testerror(int x,int y)
{ if (y==)
{
throw x;
}
cout << "计算结果:"<<x/y<< endl;
} void awrap()
{
testerror(, );
} void main()
{
//
try
{
awrap();
}
catch (int x)
{
cout << x << "不能被0整除" << endl;
}
catch (...)
{
cout << "无言的结局" << endl;
}
system("pause");
}
输出结果:
- 一个字符串比较的例子
void testerror(char * name)
{
cout << "his name is " << name << endl;
if (strcmp(name,"雨化田")==)
{
throw name;
}
cout << "原来是:" << name << "!快快进来享用广式炒面" << endl;
} int main()
{
//
char name[] = "雨化田";
char *hisname = name;
try
{
testerror(hisname);
}
catch (char *name)
{
cout << "妈爷子诶~这不是:" << name << endl;
}
catch (...)
{
cout << "无言的结局" << endl;
}
system("pause");
return ;
}
输出结果:
- 栈解旋(unwinding):当异常抛出为栈对象时,异常处理可以达到析构异常对象的效果
#include<iostream>
using namespace std; class mycoach
{
public:
friend void freeobj(mycoach &t);
mycoach(char *myname, int age,int months)
{
this->myname = myname;
this->age = age;
this->months = months;
}
~mycoach()
{
cout << "free of space" << endl;
}
private:
char *myname;
int age;
int months;
}; void freeobj(mycoach &t)
{
if (t.age < )
{
cout <<"精神可嘉~但还是年龄太小" <<endl;
throw t.age;
}
if (t.months <= )
{
cout << "精神可嘉~再练一段时间,加油" << endl;
throw t.months;
}
//throw t;
} void main()
{
char name[] = "章小军";
char *hisname = name;
mycoach mt(hisname,,);
try
{
freeobj(mt);
}
catch (int a)
{
cout << "少于规定训练时间(12个月)实际:"<<a <<"个月"<< endl;
}
catch (...)
{
cout << "无言的结局" << endl;
}
system("pause");
//return 0;
}
输出结果:
其中,按下任意键之后,执行了析构函数也就是所谓的”栈解旋“







