Java Reference
In-Depth Information
with a
try-catch
pair:
try {
int data = Integer.parseInt (getParameter ("dat"));
aFunctionSetup (data);
...
}
catch (NumberFormatException e) {
data
=
-1;
}
Here, the
Integer
class method
parseInt()
throws an instance of the
NumberFormatException
class if the string passed does not represent a valid
integer number. The program processing jumps from the line that causes the
exception (the
parseInt()
method call) to the code in the
catch
block. All
the code from the line that caused the exception to the end of the
try
block is
permanently skipped.
The
parseInt()
method in
Integer
is written something like the
following:
public static int parseInt (String s)
throws NumberFormatException {
...
...
code to check if the string is a number
...
if it isn't then
:
throw new NumberFormatException ("some error message");
...
}
The
throws NumberFormatException
phrase in the method signature indi-
cates that the method includes a
throw
statement of that type somewhere in the
method code.
We see that the
throw
statement actually creates an instance of the exception
(like everything else in Java, exceptions are class types) and causes the routine to
return with the exception thrown. The constructors for an exception may include
parameters with which you can pass useful information about the circumstances
of the exception. The catch code can then examine this information using methods
on the
Exception
class.
Java divides exceptions into two categories:
general exceptions
run-time exceptions
General exceptions
must
be handled in source code. They are also called
“checked” exceptions, meaning they must be checked for. For any method that
Search WWH ::
Custom Search