Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Throwing Exceptions 257

Exceptionis the parent of all exception subclasses. Acatchstatement will
catch the class and any subclass below it in the class hierarchy.


When you throw an exception with throw, it generally means you have not
done everything that needs to be done to take care of the exception.


An example of where this might be useful: Consider a hypothetical pro-
gram called CreditCardChecker, an application that verifies credit card
purchases. This application uses a class called CheckDatabase, which has
the following job:



  1. Make a connection to the credit card lender’s computer.

  2. Ask that computer if the customer’s credit card number is valid.

  3. Ask the computer if the customer has enough credit to make the
    purchase.


As the CheckDatabaseclass is doing its job, what happens if the credit card
lender’s computer doesn’t answer the phone at all? This kind of error is
exactly the kind of thing that the try-catchblock was designed for, and it
is used within CheckDatabaseto handle connection errors.


If the CheckDatabaseclass handles this error by itself, the
CreditCardCheckerapplication doesn’t know that the exception took place
at all. This isn’t a good idea—the application should know when a connec-
tion cannot be made so it can report this to the person using the applica-
tion.


One way to notify the CreditCardCheckerapplication is for
CheckDatabaseto catch the exception in a catchblock, and then throw it
again with a throwstatement. The exception is thrown in CheckDatabase,
which must then deal with it like any other exception.


Exception handling is a way that classes can communicate with each other
in the event of an error or other unusual circumstance.


When using throwin a catchblock that catches a parent class, such as
Exception, throwing the exception throws that class. This loses some detail
of what kind of error occurred, because a subclass such as
NumberFormatExceptiontells you a lot more about the problem than sim-
ply the Exceptionclass.


Java 7 offers a new way to keep this detail: the finalkeyword in a catch
statement.

Free download pdf