Java Reference
In-Depth Information
When method
main
is called and the throw-statement in it is executed, an
instance of class
ArithmeticException
is created and the program terminates
with the message
"/ by zero"
. In fact, the output will be the same as if a divi-
sion by zero had actually occurred.
Not all objects can be thrown. For example, you cannot throw a
JFrame
:
throw new
JFrame(); //
This statement is syntactically illegal
Only objects that are of class
Throwable
(or its subclasses) can be thrown.
Figure 10.1 contains an example of a throw-statement. Function
mod
throws
an
IllegalArgumentException
if
y
is
0
, as required by its specification.
Function
mod
could have been written without this test, in which case an
ArithmeticException
would be thrown (if
y
is
0
) when the expression
x%y
is
calculated. But by explicitly throwing the exception, we can give a better mes-
sage.
Get method mod
from page 10-2
of
ProgramLive
.
10.3
The throwable object
An object can be thrown only if it is an instance of class
Throwable
, which is in
package
java.lang
. Figure 10.2 contains the definition of class
Throwable
. We
explain its components.
Field
backtrace
automatically contains the call stack at the point where the
abnormal event occurred. Field
detailMessage
can contain a description of the
error. For example, for the abnormal event division by
0
, this field contains
" /
by zero"
. Every
Throwable
object has these two pieces of information.
There are two constructors; one allows the caller to give the detail message.
Getter method
getMessage
returns the detail message, and method
get-
LocalizedMessage
can be overridden to return a message that is particular to a
subclass. The usual method
toString
is there as well.
We do not show methods that deal with saving and printing the call stack.
Lesson
page 10-2
The root of all throwable classes
Throwable
The root of serious errors that cause termination
Error
VirtualMachineError
OutOfMemoryError
StackOverflowError
Exception
The root of exceptions that may be caught and processed
The root of exceptions that need not be checked
RuntimeException
ArithmeticException
IllegalArgumentException
NumberFormatException
IOException
ClassNotFoundException
Figure 10.3:
The hierarchy of throwable classes (a partial list)
Search WWH ::
Custom Search