throw exceptionObject;
public Card deal() {
if (cardsInDeck == 0)
throw new EmptyDeckException("Attempt to get a card from an empty deck");
cardsInDeck--;
return cards[cardsInDeck];
}
try {
// try block
code that might raise an exception
} catch (ExceptionType1 identifier1) {
// catch block
code to handle exception type 1
} catch (ExceptionType2 identifier2) {
// catch block
code to handle exception type 2
} ...
finally {
// finally block
code executed no matter what happens in try block
}Note: The finally clause is optional
try {
for (int i = 0; i < cardsRequested; i++) {
Card card = deck.deal();
hand.addCard(card);
}
} catch (EmptyDeckException e) {
System.out.println(e.getMessage());
System.out.println("You won't be given any more cards.");
}... methodName(parameter list) throws ExceptionType {
...
}
... methodName(parameter list) throws ExceptionType1, ExceptionType2, ... {
...
}Note:
public static void main(String [] args) throws IOException { ...Define a new class that is a subclass of Exception (either directly or through the inheritance hierarchy). To define an unchecked exception, extend RuntimeException. To define a checked exception, extend Exception or any subclass of Exception except RuntimeException.
/**
* Thrown when there is an attempt to remove a card from an empty deck.
**/
public class EmptyDeckException extends RuntimeException {
public EmptyDeckException() {
super();
}
public EmptyDeckException(String msg) {
super(msg);
}
}