Throwing exception in initialisation list?
If you cannot do the check in mtm::Dimensions
, it really should be there, you can use a helper function:
int throw_if_not_positive(int x) {
if (x <= 0) throw mtm::IllegalArgument();
return x;
}
Game::Game(int height, int width) :
dimensions(throw_if_not_positive(height),
throw_if_not_positive(width)),
board(height * width, nullptr)
{
}
Or use unsigned
, or use
struct positive_int {
int value;
positive_int(int x) : value(x) {
if (x <= 0) throw mtm::IllegalArgument();
}
operator int(){ return value; }
};
Game::Game(positive_int height, positive_int width) :
dimensions(height,width),
board(height * width, nullptr)
{
}
You can first catch the bad_alloc
thrown in the construction of board
, and then throw your own custom exception:
Game::Game(int height, int width) try : dimensions(height, width), board(height * width, nullptr)
{
if (height <= 0 || width <= 0) {
throw mtm::IllegalArgument();
}
}
catch(...) // or specifically bad_alloc
{
throw mtm::IllegalArgument(); // or some other custom exception
}
Here's another (better) answer that's based on your own suggestion in the comments:
Game::Game(int height, int width) :
dimensions(height, width),
board((height * width > 0 ? height * width : throw mtm::IllegalArgument()),
nullptr)
{
// ...
}
Here's a demo.
Insert a helper function to validate the height
and width
.
size_t helper(int height, int width) { if (height <= 0 || width <= 0) { throw mtm::IllegalArgument(); } return height * width; } Game::Game(int height, int width) : dimensions(height, width), board(helper(height, width), nullptr) { }