C/C++进阶学习笔记(三) 异常处理 try catch throw
来源:互联网 发布:广州锋泽网络垃圾 编辑:程序博客网 时间:2024/06/10 07:01
本节介绍C++里面的异常处理
欢迎到 我的博客 查看更详细的内容
throw
throw
可以理解为人为地抛出自定义的异常类型,可以用于代码中符合某些条件时刻意地制造一些异常信息抛出给控制台处理,比如如下例子:
Sales_item item1,item2;if(!item1.same_isbn(item2)) //当item1和item2的ISBN不同时,抛出异常 throw runtime_error("Data must refer to same ISBN");cout << item1 + item2 << endl;
try catch结构
try catch结构用于捕捉程序中会出现的异常,并对异常进行处理
try一下某句代码会不会有异常,如果有的话catch某种类型的异常,并进行处理
try{ 可能出现异常的语句;}catch(异常种类1 异常变量名1){ 处理第一种异常的语句;}catch(异常种类2 异常变量名2){ 处理第二种异常的语句;}
常见的异常种类
实例
// try_catch_throw.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <bitset>using namespace std;int main(){ bitset<100> bs; //定义bitset,可以理解为位数组 for (size_t index = 0; index != bs.size(); ++index) //用size_t访问数组位,可以动态地自我改变index的类型,避免访问不到数组的高位元素 bs[index] = index; //bs.to_ulong(); try { bs.to_ulong(); //bs的长度(100)大于ulong能存储的位数,此处会出现溢出异常 } catch (runtime_error err) //catch runtime error { cout << err.what() << endl; } try { //throw logic_error("just kidding"); throw overflow_error("just kidding"); //这里人为地抛出异常供后面的语句来catch } catch (overflow_error err) { cout << "overflow error" << endl << err.what() << endl; } catch (logic_error err) { cout << "logic error" << endl << err.what() << endl; } system("pause"); return 0;}
0 0
- C/C++进阶学习笔记(三) 异常处理 try catch throw
- 【c#】异常处理:try catch throw
- try catch throw异常处理
- 异常处理 throw try catch
- 异常处理 try catch throw
- C/C++编程异常处理中try和throw以及catch语句的用法
- 异常(try-throw-catch)
- java 进阶(1)--异常处理:try……catch,Throw处理异常和finally的用法
- Objective-c学习笔记07——异常处理(try catch)
- C++ try catch() throw 异常处理(一)
- c++ 异常处理(try catch throw)、命名空间
- C++处理异常 try,catch,throw
- C++ try catch() throw 异常处理
- C++ try catch() throw 异常处理
- C++ try catch() throw 异常处理
- C++处理异常 try,catch,throw
- C++处理异常 try,catch,throw
- C++语言处理异常 try catch throw
- MSSQL中存储过程的可选参数的定义和使用_SQL高亮显示
- 次小生成树
- Java的四种引用,强弱软虚,用到的场景。
- 解决Xcode 8 Console 输出系统网络连接log的问题
- 打印自身源代码的程序
- C/C++进阶学习笔记(三) 异常处理 try catch throw
- Recast & Detour 寻路引擎的基本流程
- 一张图说明进程, 线程, 操作系统内存管理
- 第一节-数据结构
- Collections集合框架工具类
- C语言复杂声明的本质与局限
- 数据结构——链表C/C++实现
- linux的文件目录结构
- 集合(ArrayList,HashMap,HashSet)扩容