Class X
{
public:
X();
//Pre-condition: example can't be 3.
void number(int example);
};
void X::number(int example)
{
//exception handing here
}
{
...
X* badNumber = new X();
int badExample = 3;
badNumber->number(badExample);
...
}
So what is the optimal way of handling the exception? For instance, would this be bad practice?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void X::number(int example)
{
try
{
if (example == 3)
{
throw example;
}
catch(int badNumber)
{
cout << badNumber << " is a bad number";
//Program is shut down
}
}
...
//the rest of the code
...
}
If I know that the exception can only happen at the beginning of the function, is it okay to catch it right away? Are there any problems with that?
The exception doesn't have to be thrown only at the beginning.
It can be thrown from any point of any function.
In my opinion you should let the enduser handle the exception.
Eg. The class function throws, and the caller of the function catches.
1 2 3 4
void X::number(int n){if(n== 3) throw n; //...
X x;
try{x.number(3);}
catch(int n){std::cout << n << std::endl;}
It smells. Exceptions should be thrown when you cannot handle error in current context and want to delegate responsibility to caller function.
Likewise you should catch exception when you have something to do with it: you can handle it here, you want to repackage exception, you want to log exception occurence...
BTW, in your case program will not be shut down because you handled exception.
Also you made a mistake in try...catch blocks: catch should follow try, as else follows if.
In your case you can do something like:
1 2 3 4 5 6 7
void X::number(int example)
{
if (example == 3)
//Letting caller decide what to do with exception as we do not know.
throw std::domain_error("3 is not valid number");
//...
}
std::unique_ptr<X> badNumeber = new X();
//or in C++14
auto badNumber = make_unique<X>();
badNumber will be automatically deleted when it goes out of scope, or when exception is thrown, what C-style pointers cannot promise. Also it denotes ownership on object.