Java Reference
In-Depth Information
scan.close();
}
}
}
Note that in order for the scan object to be accessible in both the
try
and
finally
blocks, it must
be declared outside either block. Now look at the try‐with‐resources block.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Resources {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)){
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);
}
}
}
By adding the declaration and initialization directly to the
try
block, the resource will automatically
be closed no matter how the rest of the
try
block completes (with or without exception). Imagine
you come back to this code later and decide to change the
System.in
scanner to some other user
interface. Simply by changing the resource in the
try
clause, you are assured that it will be closed
correctly. You can also declare more than one resource, if necessary, simply by separating the
resources with a semicolon. You will see many more examples of this in Chapter 8, where the differ-
ent tools available for reading and writing will be explained fully.
In Java, there are two types of exceptions: checked and unchecked. Specifically, the
Exception
class
has a subclass called runtime exceptions. Runtime exceptions and any subclasses are unchecked,
while all other types of exceptions are checked. Java requires that checked exceptions be handled,
and you will see this indicated with an error alert in Eclipse or other compilers. Eclipse offers two
possible solutions: declare that the method might throw a particular type of exception or enclose
particular statements in a
try/catch
designed to handle those exceptions. If you simply add a
throws
declaration, you are not handling the exception in any way; you are simply alerting any-
one who might call this method that an exception is possible. In order to handle the exceptions,
you should use a
try/catch
block. In your
main
method, the
try/catch
solution is certainly
Search WWH ::
Custom Search