This is a follow-on from my question regarding multiple catch blocks How to deal with returning an object and handling errors
My updated code is below, however I’m getting an error that my draw() method must return an int, is there any way to make the compiler recognise that endOfDeck() will return an int, thus fulfilling the return requirements? (see “return endOfDeck())
Any smarter way to accomplish this?
import java.util.ArrayList;
import java.util.ListIterator;
/**
* @author L
*
*/
public abstract class Deck
{
private ArrayList<Card> cards;
private ListIterator<Card> deckPosition = cards.listIterator();
private Card lastDrawn;
/**
*
*/
public Deck()
{
}
public int draw()
{
try
{
if(deckPosition.hasNext())
{
lastDrawn = deckPosition.next();
return 1;
}
else if(cards.isEmpty())
{
throw new EmptyDeckException();
}
else
{
throw new EndOfDeckException();
}
}
catch(EmptyDeckException e)
{
emptyDeck();
return 0;
}
catch(EndOfDeckException e)
{
return endOfDeck();
}
catch(Exception e)
{
System.out.println("Exception when drawing a card, check try/catch block in draw() method of Card");
e.printStackTrace();
}
}
public abstract int endOfDeck();
public abstract void emptyDeck();
}
Your last
catchblock does not have any return statement: –So, your method will not return any value, if that catch block is executed. May be you can return any integer denoting the exception, or wrap the exception in a
RuntimeExceptionand rethrow it.But, your code seems somewhat problematic. You are throwing exception unnecessarily. Whatever you are doing in the
catchblock, you can do directly in yourif-elseblocks.So, you can modify your code to: –