Cookie
Cookie

Reputation: 12642

C++ basic string exception

If I just want to throw a string, isn't there a built in type somewhere so that I can just do

throw standard_exception("This is wrong!");

Or do I have to define such a standard exception that derives from exception myself? I know it is very simple to do so, I just thought this would be so common that it would be defined somewhere.

Thanks

Upvotes: 2

Views: 1172

Answers (4)

Praetorian
Praetorian

Reputation: 109089

You can throw std::runtime_error or create your own class that inherits from std::exception as follows

#include <exception>
#include <string>


class myexcept : public std::exception
{
private:
  /**
   * Reason for the exception being thrown
   */
  std::string what_;

public:
  /**
   * Class constructor
   *
   * @param[in] what
   *    Reason for the exception being thrown
   */
  myexcept( const std::string& what ) : what_( what ){};


  /**
   * Get the reason for the exception being thrown
   *
   * @return Pointer to a string containing the reason for the exception being thrown
   */
  virtual const char* what() const throw() { return what_.c_str(); }


  /**
   * Destructor 
   */
  virtual ~myexcept() throw() {}
};

To throw

throw myexcept( "The reason goes here" );

Upvotes: 1

Soren
Soren

Reputation: 14688

Runtime error should be what you are looking for

throw runtime_error("This is wrong");

Upvotes: 4

templatetypedef
templatetypedef

Reputation: 372664

If you want to throw a string, you can do so by just writing

throw "I'm throwing a string!";

This isn't a particularly good idea, though, since it's not considered good form to throw things like char*s as exceptions. If you want to wrap the string into an exception of some form, you can always just use runtime_error or logic_error:

throw logic_error("This is wrong!");
throw runtime_error("This is wrong!");

Upvotes: 6

James McNellis
James McNellis

Reputation: 354979

std::runtime_error and std::logic_error (both derived from std::exception) both have constructors that take strings and override the what() member function to return the provided string.

Upvotes: 7

Related Questions