Exception in Constructor?

if i have this:
1
2
3
4
5
6
7
8
9
10
class Number
{
private: int x;
public:
 Number(int _x):x(_x)
 {
  if (_x == 0)
   //what i do here? if i don't want 0?
 }
}


What is the best thing to do in this case? Exception? If it is, how i do it?
I don't want to construct the object if it is _x == 0.
thank you very much!
To easy to understand, make the code zone of if(_x == 0) become empty then use 'else' {code}
Or put '!' before the expression comparision
1
2
if(_x == 0){} else{[...]}// if(x == 0); else {[...]}
if(!_x == 0){[...]}//if(!x){[...]}//if(x != 0){[...]} 

the point is the object still will be created and i could use it in main(). I don't want to create the object if _x == 0, or if create the object i want to delete right away so the user cant use it.
Just throw an exception. Go look up exceptions on this site.
It would be something like this:

1
2
3
4
5
6
7
8
9
10
11
#include <stdexcept>
class Number
{
private: int x;
public:
 Number(int _x):x(_x)
 {
  if (_x == 0)
   throw std::runtime_error("attempted to create Number(0)");
 }
};


Or, if you don't want x to be initialized before the check is made,

1
2
3
4
5
6
7
8
9
class Number
{
private: int x;
public:
 Number(int _x) :
        x(_x ? _x : throw std::runtime_error("attempted to create Number(0)"))
 {
 }
};
Topic archived. No new replies allowed.