Essential C++ 学习笔记(七)

7 异常处理

7.1 抛出异常 (Throwing an exception)

抛出(throw)一个异常, 所谓异常(exceptions) 是某种对象.


7.2 捕捉异常 (Catching an Exception)

可以利用单一或连串的catch子句来捕捉(catch) 被抛出的异常对象.

如果我们想要捕捉任何型别的异常, 可以用从catch-all的方式. 

catch(...)

{

log_message("");


7.3 异常提炼 (Trying for an Exception)

如果try块内有任何异常发生,便接下来由catch子句加以处理. 

在try块内外该放哪些语句, 都是程序员的责任.


7.5 标准异常 (The Standard Exceptions)

1. 如果new表达式无法从程序的自由空间(free store) 配置到足够的内存, 它会抛出bad_alloc异常对象.

2. 也可以将自己的exception class 继承于exception基类下, 首先含入标准头文件exception, 而且必须提供自己的what():

#include <exception>

class iterator_overflow : public exception {

public:

  iterator_overflow(int index, int max)

  : _index(index), _max(max)

  {}

  int index() {return _index;}

  int max() {return _max;}


  //overwrite exception::what()

  const char* what() const;


private:

  int _index;

  int _max;

};


融入标准的exception类体系的好处是, 它可以被任何打算捕捉抽象基类exception的程序所捕捉.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值