Java Reference
In-Depth Information
} catch (ArithmeticException ae){
System.out.println(ae);
System.exit(0);
}
The division and print statements will be attempted, but if an
ArithmeticException
is thrown, the
catch
block will catch it. Then the exception will be printed and the program will be terminated.
Of course, you may prefer that the program not be terminated, but continue. You can change the
statements inside the
catch
block to accomplish this.
try {
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
} catch (ArithmeticException ae){
System.out.println("Years in retirement should not be 0." +
"Default value is 20 years.");
double monthlyPension = retirementFund/20/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
Now if you run the program, it will try the original calculation, throw a division by 0 exception,
catch the exception in the
catch
block, and calculate the monthly pension using another nonāzero
value. This way, the program can execute fully.
You'll notice though, that the
catch
block was designed here to catch only exceptions of the
ArithmeticException
type. You might have more than one exception type that must be handled.
In older versions of Java, you had two choices: create a separate
catch
block for each type of excep-
tion or catch all exceptions (or even all
throwables
, which include errors and exceptions, though this
is not advised) in one generic
catch
block. Since Java 7, you can catch more than one specific type of
exception in a single
catch
block.
try {
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
} catch (ArithmeticException|NullPointerException exc){
System.out.println("Fields should not be null.");
System.out.println("Years in retirement should not be 0." +
"Default value is 20 years.");
double monthlyPension = retirementFund/20/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
You can see that if either of the specified exceptions is caught, the response in the
catch
block is
the same. In this particular case, you probably would prefer not to do this, since a
null pointer
exception
does not mean that the
yearsInRetirement
needs to be overwritten by the default
value. Therefore, it makes more sense to separate the two exceptions into two separate
catch
blocks.
Search WWH ::
Custom Search