Java Reference
In-Depth Information
System.out.print("Enter the interest rate: ");
values[1] = scan.nextDouble();
System.out.print("Enter the loan term (in years): ");
values[2] = scan.nextInt();
}
return values;
}
// method takes a double[] with three elements
// and calculates a monthly payment
public static double calculatePayment(double[] values)
throws ArithmeticException, IndexOutOfBoundsException {
double principle = values[0];
double rate = values[1];
double years = values[2];
double interest = principle * rate * years;
double total = principle + interest;
return total / years / 12;
}
}
In this example, there are three methods:
main()
,
scanValues()
, and
calculatePayment()
,
but together they accomplish the same goal as the previous example. You can see how the
throws
declaration in the “lower” methods warns that there are possible exceptions, but any
exception is not handled directly there in the method. An exception will be thrown and
caught “higher up” the chain, in the
main
method, where it is handled by the appropriate
catch
block.
This is also where you might encounter
try
blocks without
catch
blocks. When a method throws
an exception (to be caught higher up), it will interrupt the execution of the method. Therefore, you
may need a
finally
block to take care of things, like open resources, before exiting the method.
Consider just the previous
scanValues()
method. You can see that there are no
catch
blocks, so
you might use a
try/finally
here instead of the try with resources. Any exception will be thrown
up, but the scanner will be closed in the
finally
block before exiting.
// method asks for and scans three doubles:
// principle, interest rate, and loan years
public static double[] scanValues() throws InputMismatchException {
double[] values = new double[3];
Scanner scan = new Scanner(System.in);
try {
System.out.print("Enter the loan amount: ");
values[0] = scan.nextDouble();
System.out.print("Enter the interest rate: ");
values[1] = scan.nextDouble();
System.out.print("Enter the loan term (in years): ");
values[2] = scan.nextInt();
} finally {
scan.close();
}
return values;
}
Search WWH ::
Custom Search