|
|
|
Sponsored Link •
|
|
Advertisement
|
Throwing exceptions
To throw an exception, you simply use the throw keyword
with an object reference, as in:
throw new TooColdException();
The type of the reference must be Throwable or one of its
subclasses.
The following code shows how a class that represents the customer,
class VirtualPerson, might throw exceptions if the coffee
didn't meet the customer's temperature preferences. Note that Java also
has a throws keyword in addition to the throw
keyword. Only throw can be used to throw an exception.
The meaning of throws will be explained later in this
article.
// In Source Packet in file except/ex1/VirtualPerson.java
class VirtualPerson {
private static final int tooCold = 65;
private static final int tooHot = 85;
public void drinkCoffee(CoffeeCup cup) throws
TooColdException, TooHotException {
int temperature = cup.getTemperature();
if (temperature <= tooCold) {
throw new TooColdException();
}
else if (temperature >= tooHot) {
throw new TooHotException();
}
//...
}
//...
}
// In Source Packet in file except/ex1/CoffeeCup.java
class CoffeeCup {
// 75 degrees Celsius: the best temperature for coffee
private int temperature = 75;
public void setTemperature(int val) {
temperature = val;
}
public int getTemperature() {
return temperature;
}
//...
}
|
Sponsored Links
|