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的程序所捕捉.