Exception message with C++20 format

408 Views Asked by At

Similar to the this question. Needed throw a exception with a message using printf-like style instead of string cocatenation or iostreams. Using the C++ 20 Formatting Library:

  throw std::runtime_error { 
    std::format("Critical error! Code {}: {}", errno, strerror(errno)) 
  }; 

But it not feels ergonomic calling format in all exceptions with formatting, can it get better?

1

There are 1 best solutions below

7
On

Yes it can!

#include <format>
#include <stdexcept>

class runtime_exc : public std::runtime_error
{
   public:
     template <class... Args>
     runtime_exc(std::format_string<Args...> what_arg_fmt, Args&&... args)
       : runtime_error { std::format(what_arg_fmt, args...) }
     {
        
     }
};

Usage:

  throw runtime_exc { "Critical error!" };          
  throw runtime_exc {                        
    "Critical error! Code {}: {}", errno, strerror(errno) 
  };                                       

If you assemble the message with format in runtime you can use std::vformat. If needed locale you can add another constructor with it as first parameter. Note that std::format can throw.

EDIT: Barry comment, no need to move the format string and forward the arguments.