您的位置:首页 > 其它

boost:exception使用实例

2016-04-28 16:14 302 查看
1 /************************************************************************/
2 /*功能描述: boost exception使用实例                                    */
3 /*作者    : kernel_main                                                */
4 /*创建时间: 2014.6.8                                                   */
5 /************************************************************************/
6 #include <iostream>
7 #include <exception>
8
9 #include <boost/exception/all.hpp>
10
11 struct my_exception :         /* 自定义异常类 */
12     virtual std::exception,   /* 虚继承,struct默认public继承 */
13     virtual boost::exception  /* 虚继承,struct默认public继承 */
14 {
15     /* 空实现,不需要实现代码 */
16 };
17
18 /* 异常信息的类型 */
19 typedef boost::error_info<struct tag_err_no, int> err_no;
20 typedef boost::error_info<struct tag_err_str,std::string> err_str;
21
22 int main()
23 {
24     using namespace boost;
25     try
26     {
27         try
28         {
29             /* 抛出异常,存储错误码 */
30             throw my_exception() << err_no(10);
31         }
32         catch (my_exception& e) /* 捕获异常,使用引用形式 */
33         {
34             std::cout << *get_error_info<err_no>(e) << std::endl;
35             std::cout << e.what() << std::endl;
36             e << err_str("other info"); /* 向异常追加信息 */
37             throw; /* 再次抛出异常 */
38         }
39     }
40     catch (my_exception& e)
41     {
42         std::cout << *get_error_info<err_str>(e) << std::endl;
43         std::cout << e.what() << std::endl;
44     }
45     return 0;
46 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: