Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

256 HOUR 18:Handling Errors in a Program


Throwing Exceptions
Whenyou call a method of another class, that class can control how the
method is used by throwing exceptions.
As you make use of the classes in the Java class library, the compiler often
displays a message such as the following:

Output▼
NetReader.java:14: unreported exception java.net.MalformedURLException;
must be caught or declared to be thrown

Whenever you see an error stating that an exception “must be caught or
declared to be thrown,” it indicates the method you are trying to use
throws an exception.
Any class that calls these methods, such as an application that you write,
must do one of the following things:

. Handle the exception with a try-catchblock.
. Throw the exception.
. Handle the exception with a try-catchblock and then throw it.


Up to this point in the hour, you have seen how to handle exceptions. If
you would like to throw an exception after handling it, you can use a
throwstatement followed by the exception object to throw.
The following statements handle a NumberFormatExceptionerror in a
catchblock, and then throw the exception:
try {
principal = Float.parseFloat(loanText) * 1.1F;
} catch(NumberFormatException e) {
System.out.println(arguments[i] + “ is not a number.”);
throwe;
}

This rewritten code handles all exceptions that could be generated in the
tryblock and throws them:
try {
principal = Float.parseFloat(loanText) * 1.1F;
} catch(Exception e) {
System.out.println(“Error “ + e.getMessage());
throwe;
}
Free download pdf