April 3, 2007
Chapter 17 topics & Aloha to Java
Chapter 18 - parameter passing
Chapter 19 - Prolog
Chapter 17
Exceptions and exception handling
Introduction
Stated simply, the exception-handling capability of Java makes it possible for you to:
- Monitor for exceptional conditions within your program
- Transfer control to special exception-handling code (which you design) if an exceptional condition occurs
The basic concept
This is accomplished using the keywords: try, catch, throw, throws, and finally. The basic concept is as follows:
- You try to execute the statements contained within a block of code. (A block of code is a group of one or more statements surrounded by braces.)If you detect an exceptional condition within that block, you throw an exception object of a specific type.You catch and process the exception object using code that you have designed.
- You optionally execute a block of code, designated by finally, which needs to be executed whether or not an exception occurs. (Code in the finally block is normally used to perform some type of cleanup.)
class VirtualCafe {
public static void serveCustomer(VirtualPerson cust,
CoffeeCup cup) {
try {
cust.drinkCoffee(cup);
System.out.println("Coffee is just right.");
}
catch (TemperatureException e) {
// This catches TooColdException, TooHotException,
// as well as TemperatureException.
System.out.println("Coffee is too cold or too hot.");
// Deal with an irate customer...
}
// THIS WON'T COMPILE, BECAUSE THIS catch clause
// WILL NEVER BE REACHED.
catch (TooColdException e) {
System.out.println("Coffee is too cold.");
}
}
}
// In Source Packet in file except/ex4/VirtualCafe.java
// This class compiles fine.
class VirtualCafe {
public static void serveCustomer(VirtualPerson cust,
CoffeeCup cup) {
try {
cust.drinkCoffee(cup);
System.out.println("Coffee is just right.");
}
catch (TooColdException e) {
System.out.println("Coffee is too cold.");
// Deal with an irate customer...
}
catch (TemperatureException e) {
// This catches TooHotException as well
// as TemperatureException.
System.out.println(
"There's temperature trouble in this coffee.");
// Deal with an irate customer...
}
}
}
Chapter 18
Parameter passing methods
The implementation of Prolog used in the book is SWI-Prolog from the University of Amsterdam. You can download it from the SWI-Prolog web site.
