c++ - 如何抛出文件和行号错误?

标签 c++ boost

我尝试使用BOOST_THROW_EXCEPTION做到这一点,这是example:

#include <boost/throw_exception.hpp>
#include <stdexcept>
void demo_boost_throw()
{
    BOOST_THROW_EXCEPTION(std::runtime_error("boost throw std exception."));
    }
int main() {
    demo_boost_throw();
    return 0;
}

here中我们可以看到它确实包含文件
#define BOOST_THROW_EXCEPTION(x)\
        ::boost::throw_exception( ::boost::enable_error_info(x) <<\
        ::boost::throw_function(BOOST_THROW_EXCEPTION_CURRENT_FUNCTION) <<\
        ::boost::throw_file(__FILE__) <<\
        ::boost::throw_line((int)__LINE__) )

但是,当我运行该程序时,它不会打印出文件和行。

current_exception_diagnostic_information(),但这需要捕获并打印。我不想捕获它。我希望e.what()包含throw_function,throw_file和throw_line的额外信息。我怎样才能做到这一点?

最佳答案

如果您有机会访问 C++ 20 ,则可以通过以下方式轻松使用 std::source_location :

#include <string>
#include <sstream>
#include <iostream>
#include <experimental/source_location>

void throw_exception(std::string const& message,
                     std::experimental::source_location const& location = std::experimental::source_location::current()) {
    std::stringstream ss;
    ss << location.file_name()
       << ":"
       << location.line()
       << " "
       << message;
    throw std::runtime_error(ss.str());
}

int main() {
    throw_exception("Random exception");
    return 0;
}

Demo

关于c++ - 如何抛出文件和行号错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60383402/

相关文章:

c++ - 为什么 boost::asio::async_read 无法读取请求的字节数?

c++ - 如何在导入另一个库的库中修复 "invalid use of non-static member function"

c++ - 如何将我的应用程序带到窗口顶部

c++ - 哈夫曼解码算法

c++ - 与 BOOST Range 的接口(interface)

c++ - 返回指向缓存在 std::map 中的项目的指针

c++ - 我的 'show progress thread' 计数时不运行

c++ - 你能创建一个继承类的 std::map 吗?

c++ - 'uintmax_t'到 'size_t'和 'unsigned int'转换丢失的数据是多少?

boost - 在 CMake 中轻松使用 Boost,无需安装 Boost(Boost CMake 模块化)