當你面對上千萬行的項目時,當看到系統輸出了異常信息時,你是否想過,如果它能將文件名、行號等信息輸出,該多好啊,曾經爲此絞盡腦汁。
今天使用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;
}
}
我們幾乎不用修改以前的異常類,就能讓它提供更多的異常信息。