Exception handling is a very important yet often neglected aspect of writing robust software. When an error occurs in a Java program it usually results in an exception being thrown. How you throw, catch and handle these exception matters. There are several different ways to do so. Not all are equally efficient and fail safe.
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;
}
//...
}