What to throw in a C ++ class wrapping a C library?

I need to create a set of shells C++around an existing library C.

For many library objects, the Cconstruction is done by calling something like britney_spears* create_britney_spears()and the opposite function void free_britney_spears(britney_spears* brit).

If the distribution britney_spearsfails, create_britney_spears()returns NULL.

This, as far as I know, is a very common picture.

Now I want to wrap this inside a class C++.

//britney_spears.hpp

class BritneySpears
{
  public:

    BritneySpears();

  private:

    boost::shared_ptr<britney_spears> m_britney_spears;
};

And here is the implementation:

// britney_spears.cpp

BritneySpears::BritneySpears() :
  m_britney_spears(create_britney_spears(), free_britney_spears)
{
  if (!m_britney_spears)
  {
    // Here I should throw something to abort the construction, but what ??!
  }
}

So, the question is in the code example: What needs to be done to interrupt the constructor?

, , , . , . ? std ?

.

+3
3

BritneyFailedToConstruct. , ( ). std:: exception - , std:; exceptions virtual what() function. :

throw MyError( "failed to create spears object" );

, :

class Exception : public std::exception {

    public:

        Exception( const std::string & msg = "" );
        Exception( const std::string & msg, int line,
                        const std::string & file );

        ~Exception() throw();

        const char *what() const throw();
        const std::string & Msg() const;

        int Line() const;
        const std::string & File() const;

    private:

        std::string mMsg, mFile;
        int mLine;
};

#define ATHROW( msg )\
{   \
    std::ostringstream os;  \
    os << msg               \
    throw ALib::Exception( os.str(), __LINE__, __FILE__  ); \
}   \

. , :

ATHROW( "britney construction failed - bad booty value of " << booty );
+5

- (, std::exception std::exception) , .

, , ( ).

+1

I would either throw away runtime_error( link ) or an object of your own class derived from runtime_error.

+1
source

Source: https://habr.com/ru/post/1747849/


All Articles