Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: How to pass parameters to custom exceptions?

I have created a custom exception:

class MyIOException : public std::exception
{
public:
  virtual const char* what() const throw()
  {
    return "IO Exception";
  } 
};

and

class MyEmptyImageException : public MyIOException
{
private:
  std::string m_bucketName;
  std::string m_objectName;

public:

  MyEmptyImageException(const std::string& bn, const std::string& on) : m_bucketName(bn), m_objectName(on) {}
  virtual const char* what() const throw()
  {
    std::string msg = "Empty Image : " + m_bucketName + m_objectName;
    return msg.c_str();
  }  
};

And I try it like this:

int main(int argc, char** argv)
{
  try
  {
    // ... read image
    if (image.empty)
    {
      throw MyEmptyImageException(folderName, imageName);
    }
    // ... remained code
  }
  catch (MyEmptyImageException& meie)
  {
    std::cout << meie.what() << std::endl;
  }
  catch (std::exception& e)
  {
    std::cout << e.what() << std::endl;
  }
  return 0;
}

I am not sure if I have done it right, could you correct me, or suggest a better implementation, because I am a beginner in using derived exceptions?

like image 717
thedarkside ofthemoon Avatar asked May 19 '14 16:05

thedarkside ofthemoon


1 Answers

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

But, the function MyEmptyImageException::what() is incorrect because it returns msg.c_str(), where msg is allocated on the stack. When the function what() returns, them msg object is destroyed, and the char* pointer points to the buffer managed by a deallocated object. To fix that, you can construct the message in the constructor 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();
  }
};
like image 186
3 revs Avatar answered Sep 27 '22 21:09

3 revs