问题
Thanks for checking out my question. I have the following code for a java deck. I want to step away from arrays and toy code and try using best practice and object oriented principles for this one, I'm aware that I can do this in a much simpler, but less re-usable, manner.
The end goal is to create a cardgame framework which I can use to deal with the mundane parts of deck management while concentrating on the implementation of different games.
I'm having an issue with my error handling. My idea for the draw() code is as follows -
1) If there's another card return it and move the iterator along. This will eliminate the need for a discard pile as the discards will be behind the iterator with the .last() card being the one just drawn.
2) If there isn't another card and "cards" is empty run the emptyDeck() method. This method will be implemented in subclasses. For example in solitaire you may want to end the game after running through the deck x number of times so you may not want to draw a card any more.
3) if the deck isn't empty and you have no more cards then you call the endOfDeck() method which is going to be subclassed. Again, you may want to shuffle the deck or simply reset the iterator
However I'm getting the old "must return a Card" error message. I've tried creating a custom exception but I can only specify one handler method. Can anyone suggest a smart way to do this?
public abstract class Deck
{
private ArrayList<Card> cards;
private ListIterator<Card> deckPosition = cards.listIterator();
/**
*
*/
public Deck()
{
}
public Card draw()
{
Card drawn;
try
{
if(deckPosition.hasNext())
{
drawn = deckPosition.next();
}
else if(cards.isEmpty())
{
emptyDeck();
}
else
{
endOfDeck();
}
}
catch(Exception e)
{
System.out.println("Exception when drawing a card, check try/catch block in draw() method of Deck");
e.printStackTrace();
}
finally
{
return drawn;
}
}
public abstract void endOfDeck();
public abstract void emptyDeck();
}
回答1:
When a method is unable to return a meaningful result due to an internal error, the method should throw an exception instead of returning just something. So when an error occurs in your draw method which the method itself can not manage, it should throw an exception itself which is then handled by the caller.
In this case I would create a new exception class DeckEmptyException
. When the deck is empty, the draw method would throw that exception instead of returning a card. Whoever calls the draw method would then have to deal with this exception.
来源:https://stackoverflow.com/questions/14753994/how-to-deal-with-returning-an-object-and-handling-errors