我尝试使用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/