[转] 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;
    }
}

image

我们几乎不用修改以前的异常类,就能让它提供更多的异常信息。

猜你喜欢

转载自blog.csdn.net/gouguofei/article/details/104613996
今日推荐