exception 类
头文件:exception | exception.h | except.h
what() 成员返回字符串
stdexcept 异常类(头文件stdexcept)
该文件定义了 logic_error 和runtime_error 都以公有方式从exception 派生而来
invalid_argument 函数传递意料之外的值
length_error 没有足够空间执行所需操作
range_error 计算结果不在函数允许范围内
overflow_error 数据上溢错误
...
}
catch(logic_error & lo) 捕捉派生类异常
{...}
catch(exception & ex) 捕捉基类异常
{...}
catch(...) 捕捉其它所有异常
{...}
bad_alloc 异常
(从exception 类公有派生) 头文件new
内存分配问题 new分配失败抛出此异常 (以前是返回空指针)
当前C++标准提供一种标记开关
int * pi = new (std::nothrow) int; 失败返回空指针
int * pa = new (std::nowthrow) int[20]; 失败抛出异常
未捕获异常
异常未被捕获时程序调用 terminate()函数。在默认情况下 terminate()调用abort()函数结束程序
set_terminate()函数可以指定terminate()函数调用的函数,头文件exception 中声明如下
typedef void (*terminate_handler){}; //terminate_handler为无参数无返回值的函数的指针
terminate_handler set_terminate(terminate_handler f) throw() //C++98 异常规范
terminate_handler set_terminate(terminate_handler f) noexcept //C++11
void terminate(); //C++98
void terminate() noexcept; //C++11
意外异常
如果函数引发了其异常规范中没有的异常,将调用unexpected()函数,这个函数默认调用terminate(),与terminate()类似也可用set_unexpected() 替换默认函数,但unexpected_handler函数受限制,有两个功能
1.通过调用terminate()(默认行为)、abort()或exit()来终止程序。
2.引发异常
*如果新引发的异常与原来的异常规范匹配,则寻找与新异常匹配的catch块,这将用预期异常取代意外异常
*如果新引发的异常与原来的异常规范不匹配,且异常规范没包括std::bad_exception类型
,则调用terminate()。bad_exception是从exception派生出来的,声明位于exception中
*如果新引发的异常与原来的异常规范不匹配,且异常规范包括std::bad_exception类型,则不匹配的类型将被std::bad_exception异常取代
# 要捕获所有异常可用替代函数将意外异常转为std::bad_exception异常,并捕获bad_exception异常
头文件:exception | exception.h | except.h
what() 成员返回字符串
stdexcept 异常类(头文件stdexcept)
该文件定义了 logic_error 和runtime_error 都以公有方式从exception 派生而来
logic_error 类系列 描述逻辑错误 含有
domain_error 数学函数的定义域(domain)和值域(range)invalid_argument 函数传递意料之外的值
length_error 没有足够空间执行所需操作
out_of_bounds索引错误
range_error 计算结果不在函数允许范围内
overflow_error 数据上溢错误
underflow_error下溢错误
...
}
catch(logic_error & lo) 捕捉派生类异常
{...}
catch(exception & ex) 捕捉基类异常
{...}
catch(...) 捕捉其它所有异常
{...}
bad_alloc 异常
(从exception 类公有派生) 头文件new
内存分配问题 new分配失败抛出此异常 (以前是返回空指针)
当前C++标准提供一种标记开关
int * pi = new (std::nothrow) int; 失败返回空指针
int * pa = new (std::nowthrow) int[20]; 失败抛出异常
未捕获异常
异常未被捕获时程序调用 terminate()函数。在默认情况下 terminate()调用abort()函数结束程序
set_terminate()函数可以指定terminate()函数调用的函数,头文件exception 中声明如下
typedef void (*terminate_handler){}; //terminate_handler为无参数无返回值的函数的指针
terminate_handler set_terminate(terminate_handler f) throw() //C++98 异常规范
terminate_handler set_terminate(terminate_handler f) noexcept //C++11
void terminate(); //C++98
void terminate() noexcept; //C++11
意外异常
如果函数引发了其异常规范中没有的异常,将调用unexpected()函数,这个函数默认调用terminate(),与terminate()类似也可用set_unexpected() 替换默认函数,但unexpected_handler函数受限制,有两个功能
1.通过调用terminate()(默认行为)、abort()或exit()来终止程序。
2.引发异常
*如果新引发的异常与原来的异常规范匹配,则寻找与新异常匹配的catch块,这将用预期异常取代意外异常
*如果新引发的异常与原来的异常规范不匹配,且异常规范没包括std::bad_exception类型
,则调用terminate()。bad_exception是从exception派生出来的,声明位于exception中
*如果新引发的异常与原来的异常规范不匹配,且异常规范包括std::bad_exception类型,则不匹配的类型将被std::bad_exception异常取代
# 要捕获所有异常可用替代函数将意外异常转为std::bad_exception异常,并捕获bad_exception异常