C++中的异常捕获与处理:Try、Throw、Catch关键字的理解和使用
来源:互联网 发布:防sql注入最佳 编辑:程序博客网 时间:2024/06/05 04:03
一、C++异常机制使用了三个新的关键字 (SEH(结构化异常处理))
try ──标识可能出现的异常代码段
throw ──抛出一个异常
catch ──标识处理异常的代码段
二、抛出异常 throw
throw必须在 try代码块中.后边跟的值决定抛出异常的类型。
三、捕获异常 catch
出现在try代码块后,后边跟的数据决定捕获的类型
catch(...) //表示捕获所有异常
提示:
使用异常处理将带来更多的系统开销。因此慎用异常。
#include "stdafx.h"#include<iostream>#include<stdexcept>#include<fstream>#include<string>#include<vector>using namespace std;/** 也可以让readIntegerFile()抛出两种不同类型的异常。以下是实现 如果不能打开文件,则抛出invalid_argument类异常对象,如果无法读取整数,就抛出runtime_error类对象。 invalid_argument和runtime_error都是定义在<stdexcept>头文件中的类*/void readIntegerFile(const string& fileName, vector<int> &dest){ifstream istr;int temp;istr.open(fileName);if (istr.fail()){throw invalid_argument("Unable to open the file");}while (istr >> temp){dest.push_back(temp);}if (!istr.eof()) {//We did not reach the end-of-file//This means that some error occurred while reading the file//Throw an exception//文件结尾是非数字 则抛出throw runtime_error("Error reading the file.");}}int main(){vector<int> myInts;const string& fileName = "C:/Users/Administrator/Desktop/IntegerFile.txt";//main()函数可以用两个catch语句捕获invalid_argument和runtime_errortry {readIntegerFile(fileName, myInts);}catch (const invalid_argument& e) {cerr << e.what() << endl;return 1;}catch (const runtime_error& e) {cerr << e.what() << endl;return 1;}for (const auto&element : myInts) {cout << element << " ";}cout << endl;return 0;}
阅读全文
0 0
- C++中的异常捕获与处理:Try、Throw、Catch关键字的理解和使用
- 【c#】异常处理:try catch throw
- java的异常处理try, catch,throw,throws和finally
- C/C++编程异常处理中try和throw以及catch语句的用法
- 异常处理机制try-catch-finally 和 throw与throws 的区别
- Java 异常处理 try catch finally throws throw 的使用和解读(一)
- try catch finally throw throws异常捕获和抛出demo
- try catch throw异常处理
- 异常处理 throw try catch
- 异常处理 try catch throw
- Java异常处理throws,throw关键字try,catch,finally模块
- JAVA异常处理关键字:throws,throw,try,catch,finally
- JavaSE_43th_异常的捕获和处理(try-catch-finally)
- Java语言如何进行异常处理,关键字:throws、throw、try、catch、finally分别如何使用?
- 使用try和catch捕获异常
- 使用try catch抛出和捕获异常
- 关于java异常处理的几个关键字 try catch/throw/throws
- 关于java异常处理的几个关键字 try catch/throw/throws
- ZooKeeper(2)-基本介绍
- HDU 6105 Gameia(博弈+二分匹配)
- Aptana插件安装以及配置
- Android Studio集成到Genymotion模拟器
- linux中为tomcat配置虚拟路径来作为视频播放器
- C++中的异常捕获与处理:Try、Throw、Catch关键字的理解和使用
- Ration和深蓝的下午茶:取石子游戏&异或和
- CC2640之OAD固件升级(内置Flash)
- 模拟Json加载数据(添加购物车)
- 扫地机器人排行榜
- 利用matlab点云工具处理点云
- MySql中利用insert into select 准备数据uuid主键冲突
- chrome的devtool源码inspectjs
- MyEclipse里保存文件时报错