Java Reference
In-Depth Information
there to take care of really abnormal errors that the method itself cannot be
expected to handle and that should therefore be handled by the calling method
(or its caller ...).
2. Throw an exception when the method in which an abnormal event occurs
is not the best place to handle it.
For example, if you are writing a method that processes a sequence of char-
acters of a particular form and a sequence is given that does not have the form,
the error is the caller's, and the calling place is the best place to handle it.
3. Do not make try-blocks too small.
All other things being equal, it is better to have the whole body of a method
enclosed in a single try-statement with several catch clauses than to have many
smaller try-statements each with one catch clause.
4. Do not hide exceptions.
When an error message says that a checked exception needs a try-block, the
tendency is to write one hurriedly, like this one:
try {
some code
} catch (Exception ex) {}
The catch-block does nothing, and the program just goes on as if nothing
happened. You do this because you do not expect the exception to happen. But
when it does, and it takes you several days to find the problem, you will be sorry.
Key concepts
Throwable object . A throwable object is an object that is an instance of class
Throwable . Typically, it is an object of one of two subclasses of Throwable :
Error (these should not be caught and handled) and Exception (these may be
caught and handled).
Throwing an exception . Java throws an exception —an object of (a subclass
of) class Throwable — if an abnormal event happens. If it is not caught , a mes-
sage is printed and program execution aborts.
The throw statement . A program can throw an exception using the statement
throw throwable-object ; .
Catching an exception . A program can catch an exception using the try-state-
try try-block catch ( parameter-declaration ) catch-block
Checked exceptions . Every possibly-thrown exception that is not an instance
Search WWH ::

Custom Search