标准头文件 <exception> 提供了 C++ 标准中指定的类和异常相关函数。仅在标准模式(编译器缺省模式,或使用选项 -compat=5)下编译时才可访问该头文件。以下摘录的部分代码显示了 <exception> 头文件声明。
// standard header <exception>
namespace std {
class exception {
exception() throw();
exception(const exception&) throw();
exception& operator=(const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
};
class bad_exception: public exception {...};
// Unexpected exception handling
typedef void (*unexpected_handler)();
unexpected_handler
set_unexpected(unexpected_handler) throw();
void unexpected();
// Termination handling
typedef void (*terminate_handler)();
terminate_handler set_terminate(terminate_handler) throw();
void terminate();
bool uncaught_exception() throw();
}标准类 exception 是所选语言构造或 C++ 标准库抛出的所有异常的基类。可以构造、复制及销毁类型为 exception 的对象,而不会生成异常。虚拟成员函数 what() 返回描述异常的字符串。
为了与 C++ 4.2 版中所用的异常兼容,还提供了头文件 <exception.h> 以用于标准模式下。该头文件允许转换到标准 C++ 代码,并包含了不是标准 C++ 部分的声明。应在开发进度计划许可的情况下,更新代码以遵循 C++ 标准(使用 <exception> 而非 <exception.h>)。
// header <exception.h>, used for transition #include <exception> #include <new> using std::exception; using std::bad_exception; using std::set_unexpected; using std::unexpected; using std::set_terminate; using std::terminate; typedef std::exception xmsg; typedef std::bad_exception xunexpected; typedef std::bad_alloc xalloc;