Java Reference
In-Depth Information
2.5.4
the
throw
and
throws
clauses
The programmer can generate an exception by use of the
throw
clause. For
instance, we can create and then throw an
ArithmeticException
object by
The
throw
clause is
used to throw an
exception.
throw new ArithmeticException( "Divide by zero" );
Since the intent is to signal to the caller that there is a problem, you
should never throw an exception only to catch it a few lines later in the same
scope. In other words, do not place a
throw
clause in a
try
block and then han-
dle it immediately in the corresponding
catch
block. Instead, let it leave
unhandled, and pass the exception up to the caller. Otherwise, you are using
exceptions as a cheap go to statement, which is not good programming and is
certainly not what an exception—signaling an exceptional occurrence—is to
be used for.
Java allows programmers to create their own exception types. Details on
creating and throwing user-defined exceptions are provided in Chapter 4.
As mentioned earlier, standard checked exceptions must either be caught or
explicitly propagated to the calling routine, but they should, as a last resort, even-
tually be handled in
main
. To do the latter, the method that is unwilling to catch
the exception must indicate, via a
throws
clause, which exceptions it may propa-
gate. The
throws
clause is attached at the end of the method header. Figure 2.14
illustrates a method that propagates any
IOException
s that it encounters; these
must eventually be caught in
main
(since we will not place a
throws
clause in
main
).
The
throws
clause
indicates propa-
gated exceptions.
input and output
2.6
Input and output (I/O)
in Java is achieved through the use of the
java.io
pack-
age. The types in the I/O package are all prefixed with
java.io
, including, as
we have seen,
java.io.IOException
. The
import
directive allows you to avoid
using complete names. For instance, with
import java.io.IOException;
you can use
IOException
as a shorthand for
java.io.IOException
at the top of
your code. (Many common types, such as
String
and
Math
, do not require
import
directives, as they are automatically visible by the shorthands by virtue
of being in
java.lang
.)
Search WWH ::
Custom Search