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

(singke) #1
ptg7068951

Exceptions 255

Using command-line arguments to specify two arguments, you can run it
with integers, floating-point numbers, and nonnumeric arguments.


The ifstatement in Line 3 checks to make sure that two arguments are sent
to the application. If not, the program exits without displaying anything.


The NumberDividerapplication performs integer division, so the result is
an integer. In integer division, 5 divided by 2 equals 2, not 2.5.


If you use a floating-point or nonnumeric argument, a NumberFormat
Exceptionis thrown by Lines 6–7 and caught by Lines 10–11.


If you use an integer as the first argument and a zero as the second argument,
a ArithmeticExpressionis thrown in Lines 6–7 and caught by Lines 12–13.


Handling Something After an Exception


Whenyou are dealing with multiple exceptions by using tryand catch,
there are times when you want the program to do something at the end of
the block whether an exception occurred or not.


You can handle this by using a try-catch-finallyblock, which takes the
following form:


try {
// statements that might cause the exception
} catch(Exception e) {
// what to do when the exception occurs
} finally{
// statements to execute no matter what
}


The statement or statements within the finallysection of the block is exe-
cuted after everything else in the block, even if an exception occurs.


One place this is useful is in a program that reads data from a file on disk,
which you do in Hour 20, “Reading and Writing Files.” There are several
ways an exception can occur when you are accessing data—the file might
not exist, a disk error could occur, and so on. If the statements to read the
disk are in a trysection and errors are handled in a catchsection, you can
close the file in the finallysection. This makes sure that the file is closed
whether or not an exception is thrown as it is read.

Free download pdf