Reputation: 443
Now I am trying to design a class for a deck of cards. I have: Card.h
class Card {
public:
enum Suit { CLUBS = 1, SPADES, HEARTS, DIAMONDS, RED_JOKER, BLACK_JOKER };
Card(int card, Suit suit);
private:
int _card;
Suit _suit;
};
For the constructor with parameters, I am going to make a constraint on card, the range of it is 1 to 13,so I am going to write the constructor like this:
Card::Card(int card, Suit suit) throw (int) {
if (card < 1 || card > 13) {
delete this;
throw card;
}
}
I don't think the way I write the constructor is elegant. I also consider to add an enum for card. But it just works for this question. What about if I need to check a value from 1 to 100000? Could anyone give some suggestion? Thanks a lot!
Upvotes: 2
Views: 1538
Reputation: 3678
Why not make your Card number as an enum instead of a int. This makes error is reported in the compiling time
Upvotes: 2
Reputation: 120711
Have you reason to believe the constructor might in any (exceptional or not) real use scenario be called with a value outside the range? It seems unlikely to me, so I'd rather specify its behaviour for such input as undefined and don't throw any exceptions at all. While in development, you can add a good old assert
, which is rather more useful for debug purposes since it immediately tells the location of the problem and leaves, allowing to produce a straightforward core dump.
#include <cassert>
Card::Card(int card, Suit suit) {
assert(card >= 1 && card <= 13);
...
}
Upvotes: 1
Reputation: 208363
It is a good idea to check the values during construction, but you should not call delete
on this
. The system will make sure that if memory was allocated for the object it is released when the exception propagates.
A better implementation (in my opinion) would be:
Card::Card(int card, Suit suit) {
if (card < 1 || card > 13) {
throw std::runtime_error( "Invalid card value" );
}
}
Upvotes: 4