Throw very simple exception from class constructor (string only)

V

Virchanza

I have a class.

When the user creates an object of this class, it supplies three
arguments to the constructor.

The user manual for the class says what values are valid for these
three arguments.

In the event that any of the three arguments have invalid values (as
specified by the user manual), I want to throw a very simple exception
that just supplies a text explanation.

Here's what I was *hoping* I could do:

MyClass::MyClass(int a, int b, int c)
{
if (a != 6)
{
throw std::exception("a must be equal to 6!");
}
}

Of course I can't do this because std::exception doesn't have a
constructor that takes a char const*.

So here's what I've go so far:
 
V

Virchanza

Wups I hit Send too quick.

So here's what I have so far:

class SimpleException : public std::exception {

protected:

char const *const p_str;

public:

explicit SimpleException(char const *const arg)
{
p_str = arg;
}

char const *what() const throw()
{
return arg;
}
};

MyClass::MyClass(int a, int b, int c)
{
if (a != 6)
{
throw static_cast<std::exception const &>( SimpleException("a
must be equal to 6!") );
}
}

OK so I suppose I have two questions:

Do I actually have to write my own SimpleException class or is there
something similar already present in the standard library?

I'm curious, why wasn't std::exception designed so that it could take
a constructor argument specifying the "what" string? (just the way
I've done it with SimpleException).

Oh yeah... not forgetting the last question... is there an easier/
better way of doing this?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top