Java Reference
In-Depth Information
The general form of a
try/catch
block looks like this:
try {
// execute some statements
} catch (Exception exc){
// statements to handle the exception
} finally {
// no matter what, do this
}
note
While this topic refers to these as
try/catch
blocks, there are in fact
three separate components:
try,catch
, and
finally
blocks. You may encoun-
ter any of the following: a
try
block with (one or more)
catch
blocks; a
try
block with (one or more)
catch
blocks and a
finally
block; or, less commonly,
a
try
block with only a
finally
block.
Now you can see how they are used by looking again at the retirement fund examples. Recall how
you got a division by zero exception when you tried to divide an
int retirementFund
by another
int yearsInRetirement
, if the latter was given the value 0.
public class Errors {
public static void main(String[] args) {
int age = 30;
int retirementFund = 10000;
int yearsInRetirement = 0;
String name = "David Johnson";
for (int i = age; i <= 65; i++){
recalculate(retirementFund,0.1);
}
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
}
public static void recalculate(double fundAmount, double rate){
fundAmount = fundAmount*(1+rate);
}
}
You could enclose the division and print statements inside a
try
block and add a
catch
block, like
this:
try {
double monthlyPension = retirementFund/yearsInRetirement/12;
System.out.println(name + " will have $" + monthlyPension
+ " per month for retirement.");
Search WWH ::
Custom Search