Java Reference
In-Depth Information
Working with checked exceptions
Java has different rules for working with checked and unchecked exceptions. If you
write a method that throws a checked exception, you must use a
throws
clause to
declare the exception in the method signature. The Java compiler checks to make
sure you have declared them in method signatures and produces a compilation
error if you have not (that's why they're called “checked exceptions”).
a
x
Even if you never throw a checked exception yourself, sometimes you must use a
throws
clause to declare a checked exception. If your method calls a method that
can throw a checked exception, you must either include exception-handling code to
handle that exception or use
throws
to declare that your method can also throw that
exception.
For example, the following method tries to estimate the size of a web page—it uses
the standard
java.net
libraries, and the class
URL
(we'll meet these in
Chapter 10
) to
contact the web page. It uses methods and constructors that can throw various types
of
java.io.IOException
objects, so it declares this fact with a
throws
clause:
public
static
estimateHomepageSize
(
String
host
)
throws
IOException
{
URL
url
=
new
URL
(
"htp://"
+
host
+
"/"
);
try
(
InputStream
in
=
url
.
openStream
())
{
return
in
.
available
();
}
}
In fact, the preceding code has a bug: we've misspelled the protocol specifier—
there's no such protocol as
htp://
. So, the
estimateHomepageSize()
method will
always fail with a
MalformedURLException
.
How do you know if the method you are calling can throw a checked exception?
You can look at its method signature to find out. Or, failing that, the Java compiler
will tell you (by reporting a compilation error) if you've called a method whose
exceptions you must handle or declare.
Variable-Length Argument Lists
Methods may be declared to accept, and may be invoked with, variable numbers of
arguments. Such methods are commonly known as
varargs
methods. The “print for‐
matted” method
System.out.printf()
as well as the related
format()
methods of
String
use varargs, as do a number of important methods from the Reflection API
of
java.lang.reflect
.
A variable-length argument list is declared by following the type of the last argu‐
ment to the method with an ellipsis (
…)
, indicating that this last argument can be
repeated zero or more times. For example:
public
static
int
max
(
int
first
,
int
...
rest
)
{
/* body omitted for now */
}