Exceptions

Throwing an Exception

Java Syntax

throw exceptionObject;

Example

Revised deal method in Deck.java
public Card deal() {
    if (cardsInDeck == 0)
        throw new EmptyDeckException("Attempt to get a card from an empty deck");
    cardsInDeck--;
    return cards[cardsInDeck];
}

Handling an Exception: using try-catch

Java Syntax

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

Example

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.");
}

Handling an Exception: the throws clause

Java Syntax

... methodName(parameter list) throws ExceptionType { 
    ...
}

... methodName(parameter list) throws ExceptionType1, ExceptionType2, ... {
    ...
}

Note:

Example

public static void main(String [] args) throws IOException { ...

Defining an Exception

Java Syntax

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.

Example

In the file EmptyDeckException.java:
/**
 * 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);
    }
}