Alex Rivera | Logout

Something can go wrong but it is not an exception

Asked 2010-07-15T01:15:29.723
10

I am often in a situation where I have a method where something can go wrong but an exception would not be right to use because it is not exceptional.

For example:

I am designing a monopoly game. The class Bank has a method buyHouse and a field which counts the number of houses left(there is 32 houses in monopoly). Something that could go wrong is a player buying a house when there is 0 left. How should I handle this. Here is 3 approaches I can come up with.

1. public void buyHouse(Player player, PropertyValue propertyValue)
{
    if(houseCount < 0) throw new someException;
    ....
    //Not really an exceptional situation
}

2. public boolean buyHouse(Player player, PropertyValue propertyValue)
{
    if(houseCount < 0) return false;
    ....
    //This I think is the most normal approach but changing something
    //and returning if it was a success seems bad practice to me.
}

3. public boolean housesLeft()
{
    if(houseCount > 0) return true;

    return false;

    //Introducing a new method. But now I expect the client to call this method
    //first before calling buyHouse(). 
}

What would you do?

Edit
Report

1 Answer

1

This question is hard to answer without the context of which entity has-a house. From a general design perspective, there is little semantic difference for the caller between (1) and (2) - both are try and check - but you are correct that (1) is to be shunned for wholly expectable state.

answered 2010-07-15T01:25:21.243

Your Answer