Java Reference
In-Depth Information
the stage for learning about exception handling by presenting a
run()
method that
attempts to divide an integer by 0, which results in a thrown
java.lang.ArithmeticException
instance.
Listing 4-20.
Throwing an exception from the
run()
method
class ExceptionThread
{
public static void main(String[] args)
{
Runnable r = new Runnable()
{
@Override
public void run()
{
int x = 1/0;
}
};
Thread thd = new Thread(r);
thd.start();
}
}
Run this application and you will see an exception trace that identifies the thrown
ArithmeticException
:
Exception
in
thread
"Thread-0"
java.lang.ArithmeticException: / by zero
at ExceptionThread$1.run(ExceptionThread.java:10)
at java.lang.Thread.run(Thread.java:722)
Whenanexceptionisthrownoutofthe
run()
method,thethreadterminatesandthe
following activities take place:
• The JVM looks for an instance of
Thread.UncaughtExceptionHandler
installed via
Thread
's
void
setUncaughtExceptionHand-
ler(Thread.UncaughtExceptionHandler eh)
method. When this
handler is found, it passes execution to the instance's
void uncaughtEx-
ception(Thread t, Throwable e)
method, where
t
identifies the