Search code examples
c++boost

how can I throw error with file and linenumber?


I try to use BOOST_THROW_EXCEPTION to do this, here is 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;
}

From here we can see it does contain the file

#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__) )

But when I run the program, it does not print out the file and line.

There is current_exception_diagnostic_information(), but this require to catch and print. I do not want to catch it. I want the e.what() contain the extra info of throw_function, throw_file and throw_line. How can I do this?


Solution

  • If you, by any chance, have access to C++20, you can easily use std::source_location in a following manner:

    #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