【足迹C++ primer】9.try语句块和异常处理

9.try语句块和异常处理

throw表达式,异常检测部分使用throw表达式来表示它遇到了无法处理的问题。我们说throw引发了异常
try语句块,异常处理部分使用try语句块处理异常。它以多个catch子句结束。
一套异常类,用于在throw表达式和相关的catch子句之间传递异常的具体信息。

1、throw表达式

先说明这个里面用到一个throw runtime_error是包含在stdexcept头文件中的。
/*
**  功能:使程序检查之后,抛出一个异常
**  时间:2014年5月20日18:34:12
**  作者:cutter_point
*/

#include<iostream>
#include<stdexcept>

using namespace std;

int main()
{
    int i,j;
    cout<<"请输入两个数值!"<<endl;
    cin>>i>>j;

    if(i == j)      //判断两个数据是不是一样的
    {
        throw runtime_error("Data must refer to different INT");
    }

    //程序到了这里说明,两个数值是不一样的
    cout<<"The count is : "<<i+j<<endl;

    return 0;
}

2、try语句块

跟在try块之后的是一个或多个catch子句。catch子句包括三部分:关键字catch、括号内一个(可能未命名的)对象的声明(称作异常声明,exception declaration)以及一个块。

编写处理代码

/*
**  功能:try语句块的使用
**  时间:2014年5月20日18:54:00
**  作者:cutter_point
*/

#include<iostream>
#include<stdexcept>

using namespace std;

int main()
{
    int i,j;
    cout<<"输入2个数据!"<<endl;

    while(cin>>i>>j)
    {
        try
        {
            if(i == j)      //对比两个数据,不过一样那么就抛出异常
                throw runtime_error("I am so sorry! it is error!");

            cout<<"The count is : "<<i+j<<endl;
            cout<<"输入2个数据!"<<endl;
        }
        catch(runtime_error err)
        {
            //给提醒
            cout<<err.what()
                <<"\nTry Again ? Enter y or n"<<endl;
            char c; //用来检测是否需要继续还是跳出循环

            cin>>c;

            if(!cin || c == 'n')
                break;      //跳出while循环

            cout<<"输入2个数据!"<<endl;

        }
    }

    return 0;
}

3.标准异常

exception头文件定义了最通用的异常类exception。
stdexcept头文件定义了几种常用的异常类
new头文件定义了bad_alloc异常类型
type_info头文件定义了bad_cast异常类型

在 stdexcept 头文件中定义的标准异常类

exception

The most general kind of problem.

最常见的问题。

runtime_error

Problem that can be detected only at run time.

运行时错误:仅在运行时才能检测到问题

range_error

Run-time error: result generated outside the range of values that are meaningful.

运行时错误:生成的结果超出了有意义的值域范围

overflow_error

Run-time error: computation that overflowed.

运行时错误:计算上溢

underflow_error

Run-time error: computation that underflowed.

运行时错误:计算下溢

logic_error

Problem that could be detected before run time.

逻辑错误:可在运行前检测到问题

domain_error

Logic error: argument for which no result exists.

逻辑错误:参数的结果值不存在

invalid_argument

Logic error: inappropriate argument.

逻辑错误:不合适的参数

length_error

Logic error: attempt to create an object larger than the maximum size for that type.

逻辑错误:试图生成一个超出该类型最大长度的对象

out_of_range

Logic error: used a value outside the valid range.

逻辑错误:使用一个超出有效范围的值


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值