|
|
|
Sponsored Link •
|
|
Advertisement
|
throwsthrows clause the
exceptions that it may throw
throws clause indicates to client programmers what
exceptions they may have to deal with when they invoke the method
throws clause:
// In file 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.
}
}
//...
}
throws clause:
// In file VirtualCafe.java
class VirtualCafe {
public static void serveCustomer(
VirtualPerson cust, CoffeeCup cup)
throws TemperatureException,
UnusualTasteException {
try {
cust.drinkCoffee(cup);
}
catch (TooColdException e) {
System.out.println(
"This coffee is too cold.");
// Add more hot coffee...
}
}
}
throws clauses
throws clause forces client
programmers who invoke your method to deal with the exception, either by:
throws clause
Errors: For the JVM and Java API
Exception but not
RuntimeException
RuntimeException
|
Sponsored Links
|