日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

(八)boost库之异常处理

發布時間:2024/4/11 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (八)boost库之异常处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

當你面對上千萬行的項目時,當看到系統輸出了異常信息時,你是否想過,如果它能將文件名、行號等信息輸出,該多好啊,曾經為此絞盡腦汁。

????? 今天使用boost庫,將輕松的解決這個問題。

1、boost異常的基本用法

先看看使用STL中的異常類的一般做法:

// 使用STL定義自己的異常 class MyException : public std::exception { public: MyException(const char * const &msg):exception(msg) { } MyException(const char * const & msg, int errCode):exception(msg, errCode) { } }; void TestException() { try { throw MyException("error"); } catch(std::exception& e) { std::cout << e.what() << std::endl; } }

boost庫的實現方案為:

//使用Boost定義自己的異常 #include <boost/exception/all.hpp> class MyException : virtual public std::exception,virtual public boost::exception { }; //定義錯誤信息類型, typedef boost::error_info<struct tag_err_no, int> err_no; typedef boost::error_info<struct tag_err_str, std::string> err_str; void TestException() { try { throw MyException() << err_no(10) << err_str("error"); } catch(std::exception& e) { std::cout << *boost::get_error_info<err_str>(e) << std::endl; } }

?

boost庫將異常類和錯誤信息分離了,使得錯誤信息可以更加靈活,其中typedef boost::error_info<struct tag_err_no, int> err_no;

定義一個錯誤信息類,tag_err_no無實際意義,僅用于標識,為了讓同一類型可以實例化多個錯誤信息類而存在。

?

2、使用boost::enable_error_info將標準異常類轉換成boost異常類

class MyException : public std::exception{}; #include <boost/exception/all.hpp> typedef boost::error_info<struct tag_err_no, int> err_no; typedef boost::error_info<struct tag_err_str, std::string> err_str; void TestException() { try { throw boost::enable_error_info(MyException()) << err_no(10) << err_str("error"); } catch(std::exception& e) { std::cout << *boost::get_error_info<err_str>(e) << std::endl; } }

有了boost的異常類,在拋出異常時,可以塞更多的信息了,如函數名、文件名、行號。

3、使用BOOST_THROW_EXCEPTION讓標準的異常類,提供更多的信息

// 使用STL定義自己的異常 class MyException : public std::exception { public: MyException(const char * const &msg):exception(msg) { } MyException(const char * const & msg, int errCode):exception(msg, errCode) { } }; #include <boost/exception/all.hpp> void TestException() { try { //讓標準異常支持更多的異常信息 BOOST_THROW_EXCEPTION(MyException("error")); } catch(std::exception& e) { //使用diagnostic_information提取所有信息 std::cout << boost::diagnostic_information(e) << std::endl; } }

?

我們幾乎不用修改以前的異常類,就能讓它提供更多的異常信息。

總結

以上是生活随笔為你收集整理的(八)boost库之异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。