How to throw std::exceptions with variable messages?

前端 未结 8 2098
梦如初夏
梦如初夏 2020-12-04 08:00

This is an example of what I often do when I want to add some information to an exception:

std::stringstream errMsg;
errMsg << \"Could not load config          


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:40

    Ran into a similar issue, in that creating custom error messages for my custom exceptions make ugly code. This was my solution:

    class MyRunTimeException: public std::runtime_error
    {
    public:
          MyRunTimeException(const std::string &filename):std::runtime_error(GetMessage(filename)) {}
    private:
          static std::string GetMessage(const std::string &filename)
         {
               // Do your message formatting here. 
               // The benefit of returning std::string, is that the compiler will make sure the buffer is good for the length of the constructor call
               // You can use a local std::ostringstream here, and return os.str()
               // Without worrying that the memory is out of scope. It'll get copied
               // You also can create multiple GetMessage functions that take all sorts of objects and add multiple constructors for your exception
         }
    }
    

    This separates the logic for creating the messages. I had originally thought about overriding what(), but then you have to capture your message somewhere. std::runtime_error already has an internal buffer.

提交回复
热议问题