• 实验环境 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;
}

输出结果:

其中,按下任意键之后,执行了析构函数也就是所谓的”栈解旋“

最新文章

  1. iOS多线程技术方案
  2. 关于each
  3. NYOJ题目96 n-1位数
  4. oracle 根据字段分组后,将组内的数据根据字段排序
  5. java获取页面编码
  6. JAVA逻辑字符串判断真假
  7. 【PHPsocket编程专题(实战篇①)】php-socket通信演示
  8. JDBC连接数据库以及简单的操作
  9. 细谈sass和less中的变量及其作用域
  10. 更加清楚理解mvc结构
  11. C#图解教程 第十八章 枚举器和迭代器
  12. Asp.Net Core 2.0 项目实战(7)MD5加密、AES&amp;DES对称加解密
  13. PV-UV-QPS
  14. Java调用第三方接口示范
  15. 使用反向代理的http的请求流程
  16. P2430严酷的训练
  17. RabbitMQ上手记录–part 5-节点集群高可用(多服务器)
  18. mysql 判断两个字符串是否存在包含关系-------(1,2,3)与(2,3)
  19. windows kvm虚拟机安装
  20. mysql导出数据很快,导入很慢

热门文章

  1. LeetCode 611. 有效三角形的个数(Valid Triangle Number)
  2. linux terminal 快捷键
  3. enum类型的标签内容根据语言的取法
  4. SAS学习笔记63 如何导出Log
  5. 记录用到的mssql的几个方法
  6. 每周分享五个 PyCharm 使用技巧(六)
  7. opencv 源码分析 CUDA可分离滤波器设计 ( 发现OpenCV的cuda真TM慢 )
  8. 【洛谷 P2444】 [POI2000]病毒(AC自动机)
  9. ios手机app消息推送
  10. FreeRTOS任务运行时间信息统计