C++异常处理(一)----基本语法
2024-08-22 21:07:12
- 实验环境 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;
}
输出结果:
其中,按下任意键之后,执行了析构函数也就是所谓的”栈解旋“
最新文章
- iOS多线程技术方案
- 关于each
- NYOJ题目96 n-1位数
- oracle 根据字段分组后,将组内的数据根据字段排序
- java获取页面编码
- JAVA逻辑字符串判断真假
- 【PHPsocket编程专题(实战篇①)】php-socket通信演示
- JDBC连接数据库以及简单的操作
- 细谈sass和less中的变量及其作用域
- 更加清楚理解mvc结构
- C#图解教程 第十八章 枚举器和迭代器
- Asp.Net Core 2.0 项目实战(7)MD5加密、AES&;DES对称加解密
- PV-UV-QPS
- Java调用第三方接口示范
- 使用反向代理的http的请求流程
- P2430严酷的训练
- RabbitMQ上手记录–part 5-节点集群高可用(多服务器)
- mysql 判断两个字符串是否存在包含关系-------(1,2,3)与(2,3)
- windows kvm虚拟机安装
- mysql导出数据很快,导入很慢