ptg7068951
258 HOUR 18:Handling Errors in a Program
try {
principal = Float.parseFloat(loanText) * 1.1F;
} catch(final Exception e) {
System.out.println(“Error “ + e.getMessage());
throwe;
}
That finalkeyword in catchcauses throwto behave differently. The spe-
cific class that was caught is thrown.
Ignoring Exceptions
The last technique that is covered this hour is how to ignore an exception
completely. Amethod in a class can ignore exceptions by using a throws
clause as part of the method definition.
The following method throws a MalformedURLException, an error that can
occur when you are working with web addresses in a Java program:
publicloadURL(String address) throwsMalformedURLException {
URL page = new URL(address);
loadWebPage(page);
}
The second statement in this example creates a URLobject, which repre-
sents an address on the Web. The constructor method of the URLclass
throws a MalformedURLExceptionto indicate that an invalid address is
used, so no object can be constructed. The following statement causes one
of these exceptions to be thrown:
URL source = new URL(“http:www.java24hours.com”);
The string http:www.java24hours.comis not a valid URL. It’s missing
some punctuation—two slash characters (//) after the colon.
Because the loadURL()method has been declared to throw
MalformedURLExceptionerrors, it does not have to deal with them inside
the method. The responsibility for catching this exception falls to any
method that calls the loadURL()method.
Throwing and Catching Exceptions
For the next project, you create a class that uses exceptions to tell another
class about an error that has taken place.