Java Reference
In-Depth Information
In this example, if the monthlyPension calculation succeeds without any exception, then Finally
was reached. will be printed to the console. If the monthlyPension calculation throws an
ArithmeticExeption , the Finally was reached. will still be printed to the console. If the calcu-
lation throws a NullPointerException , the program will terminate and Finally was reached.
will not be printed. The last case, which perhaps was not considered, is if an exception is thrown but
not one of the ones in the catch blocks, say an IndexOutOfBoundsException . Then the exception
will be thrown, Finally was reached. will be printed to the console, and the unhandled excep-
tion will cause the program to crash.
You will see finally blocks commonly used to ensure that resources, like databases, are closed
whether the update was successful or not. A feature added in Java 7, however, makes this even
easier. The so‐called try‐with‐resources block automatically ensures the resources are closed without
the need for a finally block. You will see more in‐depth examples in the chapter on input and out-
put, but a short example is provided here to demonstrate the similarities and differences with more
traditional try‐catch‐finally blocks.
Some concepts haven't been covered quite yet, but it is sufficient to know that Scanner objects can
be used to scan simple text and parse primitive types or strings. Here it is scanning System.in ,
which includes user input to the console. The nextInt() and nextDouble() methods parse int s
and doubles from the text entered by the user. If a user enters the character 5 , the nextInt()
method will parse an int with value 5. If a user enters the word employee , this cannot be parsed
using the nextInt() method and an InputMismatchException will be thrown.
First, look at how this was done using try and finally blocks.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Resources {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
try {
System.out.print("Enter the loan amount: ");
double principle = scan.nextDouble();
System.out.print("Enter the interest rate: ");
double rate = scan.nextDouble();
System.out.print("Enter the loan term (in years): ");
double years = scan.nextInt();
double interest = principle*rate*years;
double total = principle + interest;
double payment = total/years/12;
DecimalFormat df = new DecimalFormat ("0.##");
System.out.println("Monthly payment: $"
+ df.format(payment));
} catch (Exception exc){
System.out.println(exc);
} finally {
Search WWH ::




Custom Search