Java Reference
In-Depth Information
Q UALITY T IP 11.3
Do Not Use catch and finally in
the Same try Statement
It is tempting to combine catch and finally clauses, but the resulting code
can be hard to understand. Instead, you should use a try/finally statement to
close resources and a separate try/catch statement to handle errors. For
example,
try
{
PrintWriter out = new PrintWriter(filename);
try
{
// Write output
}
finally
{
out.close();
}
}
catch (IOException exception)
{
// Handle exception
}
Note that the nested statements work correctly if the call out.close() throws
an exceptionÈŒsee Exercise R11.18.
11.6 Designing your Own Exception Types
Sometimes none of the standard exception types describe your particular error
condition well enough. In that case, you can design your own exception class.
Consider a bank account. Let's report an InsufficientFundsException when
an attempt is made to withdraw an amount from a bank account that exceeds the
current balance.
if (amount > balance)
{
throw new InsufficientFundsException(
513
514
Search WWH ::




Custom Search