Java Reference
In-Depth Information
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.");
} catch (NullPointerException np){
System.out.println("Fields should not be null.");
System.exit(0);
}
Alternatively, you can also use a very generic catch block to catch all throwables, both errors and
exceptions. In practice, it is better to be as specific as possible, so that you have the best chance at
properly handling any foreseeable exceptions.
try {
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
} catch (Throwable thrown){
System.out.println(thrown);
System.exit(0);
}
Thus far, you haven't seen the finally block in action. A finally block includes the statements
you want to execute regardless of the outcome of the try block. When you try something, if it
throws an exception or not, you still want to make sure certain things are done. You could do this
by adding these statements to both the try and catch blocks, because that would mean they are
executed in either case. However, as you've seen so far, it's best to avoid duplicate code for readabil-
ity and maintainability later. Therefore, it's better to use a finally block for this. You should note
that a System.exit() call will always immediately terminate the program and, in this case, the
finally block, or anything after the exit call, would not be executed.
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.");
} catch (NullPointerException np){
System.out.println("Fields should not be null.");
System.exit(0);
} finally {
System.out.println("Finally was reached. ");
}
Search WWH ::




Custom Search