As you may have guessed from the examples above, the Java language requires that a method declare in a throws clause the exceptions that it may throw. A method's throws clause indicates to client programmers what exceptions they may have to deal with when they invoke the method.
For example, the drinkCoffee() method of class VirtualPerson, shown below, declares three exceptions in its throws clause: TooColdException, TemperatureException, and UnusualTasteException. These are the three exceptions that the method throws but doesn't catch. The method also may throw TooHotException, but this exception doesn't appear in the throws clause because drinkCoffee() catches and handles it internally. Only exceptions that will cause a method to complete abruptly should appear in its throws clause.
// In Source Packet in file except/ex7/VirtualPerson.java
class VirtualPerson { public void drinkCoffee(CoffeeCup cup) throws TooColdException,
TemperatureException, UnusualTasteException { try { int i = (int) (Math.random() * 4.0);
switch (i) { case 0:
throw new TooHotException();
case 1:
throw new TooColdException();
case 2:
throw new UnusualTasteException();
default:
throw new TemperatureException();
}
}
catch (TooHotException e) { System.out.println("This coffee is too hot."); // Customer will wait until it cools to an
// acceptable temperature.
}
}
//...
}
In the drinkCoffee() method above, each exception declared in the throws clause is explicitly thrown by the method via a throw statement. This is one of two ways a method can complete abruptly. The other way is by invoking another method that completes abruptly.
Although a throws clause lists exceptions that may cause a method to complete abruptly, the list is not necessarily complete. Not everything that can be thrown by a method need be put in a throws clause.