简体   繁体   中英

C++ Custom exception throw () in constructor

So I read that you aren't supposed to have anything other than basic types in a custom exception class because otherwise it might throw an exception within the exception (like a dream within a dream). And that you should throw by value and catch by ref.

I have this as my exception class header:

class DeepthroatException : public std::runtime_error {
  public:
  DeepthroatException(const char* err); // set err member to err

  private:
  // Error description
  const char* err;
};

But I dont like it since it introduces an issue with memory management, which is invisible to the naked eye and I need to use a mine detector. I would like to change to an std::string if possible.

But then there is the issue in the first paragraph above, so I thought about doing this:

#include <string>
class DeepthroatException : public std::runtime_error {
  public:
  DeepthroatException(std::string err) throw(); // set err member to err, no throw

  private:
  // Error description
  std::string err;
};

Is this ok to do?

Using std::string can also give you a bad time with std::bad_alloc . But that problem is already inherent to std::runtime_error , as its constructors can take a std::string as an argument:

explicit runtime_error( const std::string& what_arg );
explicit runtime_error( const char* what_arg );

It's only this way because copying exceptions shall never throw, so the implementation will likely allocate another string and copy the argument's content to it. If you really don't want a second exception being thrown, mark your constructor as noexcept and make sure it never fails, and if it ever do, your program will be shut down immediately.

You can inherit std::runtime_error behavior by just constructing it with a string from your constructor like so:

DeepthroatException(const std::string& err) noexcept :
    std::runtime_error(err)
{
    // ...
}

At this point, you can remove your err data member, as runtime_error will give you the internal string which you can refer to by what() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM