C++异常处理实战

一 点睛

try语句块中的代码被正常执行。如果有例外发生,代码必须使用关键字throw和一个参数来抛出一个例外。这个参数可以是任意有效的数据类型,它的类型反映了例外的特征。

如果有例外发生,也就是说try语句块中有一个throw指令被执行了,catch语句块就会被执行,用来接收throw传来的例外参数,

二 异常处理的例子

1 代码

#include <iostream>
using namespace std;
int main() {
    char myarray[10];
    try {
        for (int n = 0; n <= 10; n++) {
            if (n > 9) throw "Out of range";
            myarray[n] = 'z';
        }
    }
    catch (char const* str)
    {
        cout << "Exception: " << str << endl;
    }
    catch(...)
    {
        cout << "catch ..." <<endl;
    }
    cout << "cotinue" <<endl;
    return 0;
}

2 运行

[root@localhost test]# ./test
Exception: Out of range
cotinue

3 说明

程序在catch(...)分支执行完后,最后紧跟着catch语句块继续往下执行,本例就是cout << "continue" <<endl;

三 多个catch块的异常处理

1 代码

#include <iostream>
using namespace std;
int main() {
    try {
        char * mystring;
        mystring = new char[10];
        // 要求10个字符的空间不够而抛出异常,这种情况很少发生,但是可能发生
        if (mystring == NULL) throw "Allocation failure";
        for (int n = 0; n <= 10; n++) {
            // n超过mystring最大索引值,这种情况下抛出的例外将会catch(int i)捕获
            if (n > 9) throw n;
            mystring[n] = 'z';
        }
    }
    catch (int i) {
        cout << "Exception: ";
        cout << "index " << i << " is out of range" << endl;
    }
    catch (char const* str) {
        cout << "Exception: " << str << endl;
    }
    catch (...) //该分支捕获所有的例外,不管是什么类型的参数,这种情况是在括号中用三个点表示
    {
    }
    return 0;
}

2 运行

[root@localhost test]# g++ test.cpp -g -o test
[root@localhost test]# ./test
Exception: index 10 is out of range

四 标准异常的例子

1 代码

#include <iostream>
using namespace std;
#include <exception>
#include <typeinfo>

class A
{
    virtual void f(){};
};

int main() {
    try {
        A *a = NULL;
        typeid(*a); //C++标准语言库的函数也会抛出一些例外
    }
    catch (exception& e) {
        cout << "Exception: ";
        cout << e.what() << endl;
    }
    catch (...) {
        cout << "other Exception: " << endl;
    }
    return 0;
}   

2 运行

[root@localhost test]# ./test
Exception: std::bad_typeid

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值