Java Reference
In-Depth Information
Classroom Q & A
Q: When do you handle an exception and when do you declare an
exception?
A: A good question. The answer is based on design decisions. Do you
want a method to deal with a problem, or do you want the prob-
lem to be passed on to the caller of the method?
Q: I would think a method should deal with its own problems.
A: I agree, if the problem is related to the method. For example, sup-
pose that I walk into my bank and make a deposit (by invoking a
deposit() method), but the teller is having problems with his com-
puter. That should not be my problem. In this case, the deposit()
method should handle this exception and fix the problem without
notifying me, the caller of the method.
Q: Then why would the deposit() method throw an exception?
A: Well, if I am in the middle of a deposit and the bank's computer
system fails, that might be my problem. In that case, I want to be
informed that my deposit did not successfully go through. The
deposit() method can tell me that the transaction was unsuccess-
ful by throwing an exception back to me.
Q: Why not just have the method return a boolean? If the deposit
worked, it returns true. Otherwise, it returns false.
A: Well, that is a common programming design. In fact, the C and
C++ Windows API is filled with methods that return true or false.
What I don't like about getting back an answer like false is that it
doesn't tell me what went wrong. If I make a deposit and the teller
simply says, “Sorry, that didn't work,” I have no idea why. If the
teller throws me an exception instead, I can catch the exception
(which is a Java object) and determine all sorts of information
about what went wrong.
Q: Throwing the exception seems like too much overhead. Is it worth it?
A: Exception handling is a part of Java, and the minimal overhead
involved should not be a concern compared to the design bene-
fits. For example, if I try to withdraw more money than I have in my
checking account, just telling me that it did not work with a return
value of false does not stop me from ignoring my overdraft. I can
just go right on spending more money and then plead ignorance
when my overdraft statement comes in the mail. I can tell the bank
that I didn't check the return value of the withdraw() method.
Search WWH ::




Custom Search