Showing posts with label checked. Show all posts
Showing posts with label checked. Show all posts

Thursday, September 15, 2011

Checked Exceptions

Checked exceptions must be declared on the method and must be caught (or allowed to raise up) by the caller. Here's an example that creates a checked exception (NoTicketsAvailableException) by extending Exception. The buyTicket() method in Theatre throws this exception when there are no tickets to sell.

browse

package org.megha.blog.example.part9;

/** An exception thrown when no tickets are available */
public class NoTicketsAvailableException extends Exception {
}

package org.megha.blog.example.part9;

/**
 * A theatre that sells tickets.
 */
public class Theatre {

	int availableTickets;

	/** creates a new theatre with a fixed number of tickets */
	public Theatre(int availableTickets) {
		this.availableTickets = availableTickets;
	}

	/**
	 * Sells a ticket to the buyer.
	 *
	 * @return a unique ticket id representing the ticket sold
	 * @throws NoTicketsAvailableException when all tickets are sold out
         */
	public int buyTicket() throws NoTicketsAvailableException {
		if (availableTickets == 0) {
			throw new NoTicketsAvailableException();
		}
		return availableTickets--;
	}

	public static void main(String args[]) {
		// create a new threatre with only 3 seats/tickets
		Theatre theatre = new Theatre(3);

		for (int i = 1; i <= 5; i++) {
			try {
				int ticketId = theatre.buyTicket();
				System.out.println("Ticket #" + i + " is " + ticketId);
			} catch (NoTicketsAvailableException e) {
				System.out.println("Could not buy ticket #" + i);
			}
		}
	}
}