[ACCEPTED]-C++: How to pass parameters to custom exceptions?-exception-handling

Accepted answer
Score: 19

You have correctly passed the parameters 8 to the constructor of your exception class.

But, the 7 function MyEmptyImageException::what() is incorrect because it returns 6 msg.c_str(), where msg is allocated on the stack. When 5 the function what() returns, them msg object is destroyed, and 4 the char* pointer points to the buffer managed 3 by a deallocated object. To fix that, you 2 can construct the message in the constructor 1 of MyEmptyImageException itself:

class MyEmptyImageException : public MyIOException
{
  std::string m_msg;
public:

  MyEmptyImageException(const std::string& bn, const std::string& on)
    : m_msg(std::string("Empty Image : ") + bn + on)
  {}

  virtual const char* what() const throw()
  {
    return m_msg.c_str();
  }
};

More Related questions