The Java language make use exceptions to provide the error handling capabilities for all its programs.
Here you will learn what does an exception mean,
A D V E R T I S E M E N T
how to throw and catch the exceptions, what
to do with the exception once you have caught it, and how to make best use of the exception class
hierarchy provided by Java development environment.
What is an Exception?
Definition: An exception is an event which occurs during execution of the program which
disrupts the normal flow of the instructions.
Different types of errors can cause exceptions: problems which range from serious
hardware errors, such as hard disk crash, to the simple programming errors, like trying
to access the out-of-bounds array element. When such error occurs within a Java
method, the method will create an exception object and hands it to the runtime system.
The exception object do contains the information about exception including its type and
state of the program when error occurred. Runtime system is then responsible
to find some code to handle error. In the Java terminology, creating exception
object and handing it to runtime system is called "throwing an exception".
Hotjava's Catch or Declare Requirement
import java.io.*;
import java.util.Vector;
class ListOfNumbers
{
private Vector victor;
final int size = 10;
public ListOfNumbers ()
{
int i;
victor = new Vector(size);
for (i = 0; i < size; i++)
victor.addElement(new Integer(i));
}
public void writeList()
{
PrintStream pStr = null;
System.err.println("Entering try statement");
int i;
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("OutFile.txt")));
for (i = 0; i < size; i++)
pStr.println("Value at: " + i + " = " + victor.elementAt(i));
pStr.close();
}
}
The example above defines and implements the class called "ListOfNumbers". Upon
construction, the ListOfNumbers class creates a Vector which contains ten Integer
elements with sequential values 0 through 9. ListOfNumbers class also defines the
method "writeList()" that writes the list of numbers into the text file
"OutFile.txt".
The writeList() method calls up two more methods that can throw exceptions.
First,
pStr = new PrintStream(new BufferedOutputStream(new FileOutputStream("OutFile.txt")));
This line invokes the constructor for FileOutputStream which throws an IOException
when the file cannot be opened for any of the reason.
This method will throw ArrayIndexOutOfBoundsException if you pass an index whose value
is very small (negative number) or very large (larger than number of elements
contained by the Vector currently).
If you try to compile ListOfNumbers class, the compiler prints the error
message about an exception thrown by FileOutputStream constructor, but it will not
display the error message about an exception thrown by elementAt(). This is because
the exception thrown by the FileOutputStream constructor, IOException, is non-runtime
exception and the exception thrown by elementAt() method,
ArrayIndexOutOfBoundsException, is the runtime exception. Java requires only to
catch or declare non-runtime exceptions.
Catch and Handle an Exception
The first step for constructing an exception handler is to enclose statements that
might throw exception within the try block. In general, try block looks something
like this:
try
{
Java statements
}
The segment "Java statements" in the code above consists one or more legal Java
statements which could potentially throw an exception.
To construct the exception handler for writeList() method from ListOfNumbers
class, we need to enclose the exception-throwing statements of writeList() method
within the try block. There are more than one ways to accomplish this task: we can put
each statement which may potentially throw the exception within its own try statement,
and provide the separate exception handlers for each of the try. Or you can put all
the writeList() statements within the single try statement and associate multiple handlers
to it. The following example uses single try statement for the entire method as
the code tends to be easier to read.
PrintStream pstr;
try
{
int i;
System.err.println("Entering try statement");
pStr = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("OutFile.txt")));
for (i = 0; i < size; i++)
pStr.println("Value at: " + i + " = " + victor.elementAt(i));
}
The try statement governs the statements enclosed within it and it defines the
scope of any exceptions handlers (which are established by subsequent catch blocks)
associated with it. In other words, if an exception does occurs within the try
statement, then that exception is handled by some appropriate exception handler
which is associated with this try statement.
The catch Block(s)
As studied before, the try statement defines the scope of the associated exception
handlers. We do associate exception handlers with a try statement
by providing one or more of the sequential catch blocks directly after a try block.
Catch statement governs series of legal Java statements. These statements are
executed when the exception handler is invoked. The runtime system invokes
exception handler when a exception whose type matches with that of catch statement's
argument is thrown within handler's try block.
The writeList() method from ListOfNumbers class uses two exception handlers for the
try statement, one handler for each of the two types of exceptions which can be
thrown within a try block, ArrayIndexOutOfBoundsException and IOException.