【day0402】C++标准异常
来源:互联网 发布:gta5n卡掉帧如何优化 编辑:程序博客网 时间:2024/06/05 05:26
C++定义了很多的标准异常,常见的如下:
//exception
//runtime_error
//range_error
//overflow_error
//underflow_error
//domain_error
//invalid_argument 参数异常
//length_error
//out_of_range 范围异常
//bad_alloc 内存分配异常
Demo1:内存分配异常
#include <iostream>using namespace std;class Ram{public: Ram(){ p = new int[1000000]; }private: int *p;};int main(){ Ram *ram; try{ for (int i = 0; i < 10000; ++i){ ram = new Ram(); cout << i << "new successfully!\n"; } }catch(bad_alloc err){ cout << "new failed!\n"; } return 0;}
输出:
Demo2:参数异常
#include <iostream>#include <string>#include <bitset>#include <stdexcept> //标准异常//<exception>定义了与异常处理相关的类,声明和函数。//<stdexcept>定义了一些标准的异常类。分为两大类:逻辑错误和运行时错误。其中运行时错误是程序员不能控制的。// 逻辑错误都继承自logic_errorusing namespace std;/*参数异常*/int main(){ int i = 0; try{ i = 1; string str1("1010110101"); bitset<10> b1(str1); cout << "bitset b1 is OK!\n"; i = 2; //中间插入非数字字符 string str2("1101X10101"); bitset<10> b2(str2); cout << "bitset b2 is OK!\n"; }catch(invalid_argument err){ cout << "bitset error: b" << i << err.what() << endl; } return 0;}
输出:
Demo3:范围异常
#include <iostream>#include <stdexcept>using namespace std;/*范围异常*/class Stu{public: Stu(int age){ if (0 > age || 140 < age){ throw out_of_range("年龄超出范围(0~140)"); } this->age = age; }private: int age;};int main(){ int i = 0; try{ i = 1; Stu tom(22); cout << "22岁的学生" << endl; i = 2; Stu mike(155); cout << "155岁的学生" << endl; }catch(out_of_range err){ cout << "年龄错误:学生" << i <<": " << err.what() << endl; } return 0;}
输出:
1 0
- 【day0402】C++标准异常
- 【day0402】C++异常处理---错误但能处理的
- 标准异常
- 标准异常
- 标准异常
- 【day0402】C++引用形参
- [C++]详解异常处理(Exception Handling) 及标准库异常处理类
- c标准
- C + +标准
- C标准
- c标准
- C标准
- 标准C++异常处理
- 异常处理标准
- 异常事件标准格式
- Python标准异常
- C++标准异常类
- C++标准异常类
- 拼图响应式前端框架版响应式后台正式发布
- c语言中static 函数和普通函数的区别?
- 矩阵快速幂专题(二)
- MySQL多表查询
- u-boot网络启动分析(二) 驱动注册
- 【day0402】C++标准异常
- 【bzoj3329】【Xorequ】【数位dp+矩阵乘法】
- 10008---Trail ~ Testing the DAO
- Android Service通信
- 安卓开发中利用java代码修改控件位置
- [BZOJ3130][Sdoi2013]费用流 做题笔记
- 【HowTo ML】正则化
- FATAL EXCEPTION: main 2. java.lang.NoSuchFieldError: R$id.r1
- C语言如何实现一个函数返回另一个函数