Page contents © by Samuel Marateck 2007
When the JVM finds a run-time error in executing a
program, it throws an exception. This means it terminates the execution and
prints a trace of the contents of the run-time stack. This stack is used
to store local variables and addresses of the next statment to be executed when
a method is invoked. There are several types of exceptions; but they are all
subclasses of Throwable. The two direct subclasses of
Throwable are Error and Exception.
- The Error class covers errors in the system that you cannot correct,
such as errors in the run-time system. You cannot alter your program to
detect these errors.
- The Exception class covers two types of errors. The first are called
checked errors and they extend Exception.
You must alter your program to recognize these errors.
An example of a checked error is the IOException which monitors
input/output. So for instance if you read bytes from the console, with for
example System.in.read(b), you must place this statement in a
try-catch block or write throws IOException after the method
header. This is called checking the exception. A class that inherits
from Exception must be checked. You can write
your own class that inherits from the Exception class, for instance:
public class NegativeNumber extends Exception
public NegativeNumber(String s)
You can throw this exception when a negative integer ais encountered
if( a <0) throw new NegativeNumber(a + " a negative value was encountered");
However, the method containing this would need throws NegativeNumber
to immediately follow the heading.
The second type of exception is called an unchecked exception. These
exception classes extend RuntimeException which itself extends
Exception. The JVM automatically throws the API versions of these
exceptions when certain run-time exceptions are encountered. For instance the
JVM throws an IndexOutOfBoundsException exception when an array index
exceeds the limit indicted by the array dimension. You don't have to check for
this, hence the term unchecked exception. If you write your own
unchecked exception you don't indicate in the heading of the method that's
calling the exception that you are throwing the exception; however, you must
throw the exception.
SAT Jan 20 22:23:14 EST 2007