Re: Where shoul I throw RuntimeException
dimka wrote:
I want to know, where can I use runtime exceptions?
Runtime exceptions - trap conditions the client programmer should have
known better than to cause. Example - NullPointerException for a null
argument. The programmer should not pass a null argument, and will
fix the code if they discover this exception.
Checked exceptions - trap conditions in order to force the client code
to deal with it, usually not due to misuse of the call but to
situations outside of the client code's control. Example -
SQLException for an unexpected database state. There really is
nothing wrong with the code, the database just happened to be in a
different state this time. The API writer anticipated this, and put
the exception into the method signature to make sure that the client
code handles these "expected exceptions". It is unlikely that such
code will be rewritten just because this exception happens, and
there's no need or desire to halt the program for it.
Return a default value such as 'null' - when it makes sense in the
business logic that the condition is not exceptional but maps cleanly
to the range of the method. Example - returning 'null' if a record is
not found. "Not found" is a normal and expected result of a search,
and the client code will have conditional logic for this eventuality.
In this example, I can return null and describe this in javadoc [sic] for
method. But, when other developer use this method, he cann't get id
from somewhere, he must know that object with this id exist...
One period suffices to end a sentence.
If the method returns 'null' for an ID, doesn't that mean that no
object with this ID exists?
Ever, when I should make a choice, I cann't choose right answer :(
The right answer is the one you decide is right.
The Zen answer is, "Do what makes sense for the situation." It might
be different each time.
Part of the business of the API writer, even for use in one's own
client code, is to determine how clients will use the API, and prevent
abuse of the API.
--
Lew