4.9.8 高级议题
本节讨论关于exception库的一些高级议题。
对异常信息打包
exception支持使用boost::tuple(参见7.5节,第271页)对异常信息进行组合打包,当异常信息类型很多又经常成组出现时可以简化抛出异常的编写。例如:
- //tuple类型定义
- typedef tuple<errinfo_api_function, errinfo_errno > err_group;
- try
- {
- //使用enable_error_info包装自定义异常
- throw enable_error_info(std::out_of_range("out"))
- << err_group("syslogd",874);
- }
- catch (boost::exception& )
- {
- cout << current_exception_diagnostic_information()<<endl;
- }
有关tuple的更多信息,请参考7.5节,第271页。
类型转换
模板函数current_exception_cast<E>()提供类似标准库的转型操作,它类似于current_exception_diagnostic_information(),只能在catch块内部使用,可以把异常对象转型为指向E类型的指针,如果异常对象无法转换成E*,则返回空指针。
例如下面的代码把boost::exception转型成为了std::exception,前提是异常必须是std::exception的子类:
- catch (boost::exception& )
- {
- cout << current_exception_cast<std::exception>()->what();
- }
线程间传递异常
exception库支持在线程间传递异常,这需要使用boost::exception的clone能力。使用enable_current_exception()包装异常对象或者使用throw_exception()都能够包装异常对象使之可以被clone。
当发生异常时,线程在需要catch块调用函数current_exception()得到当前异常对象的指针exception_ptr对象,它指向异常对象的拷贝,是线程安全的,可以被多个线程同时拥有并发修改。rethrow_exception()可以重新抛出异常。
示范在线程中处理异常的代码如下:
- void thread_work() //线程工作函数
- { throw_exception(std::exception("test"));}
- int main()
- {
- using namespace boost;
- try
- {
- thread_work();. //启动一个线程,可能抛出异常
- }
- catch (... )
- {
- exception_ptr e = current_exception();
- cout << current_exception_diagnostic_information();
- }
- }