Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions


The try Block

The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this:
try {
    Java statements
}
The segment of code labelled Java statements is composed of one or more legal Java statements that could potentially throw an exception.

To construct an exception handler for the writeList() method from the ListOfNumbers class, you need to enclose the exception-throwing statements of the writeList() method within a try block. There is more than one way to accomplish this task: you could put each statement that might potentially throw an exception within its own try statement, and provide separate exception handlers for each try. Or you could put all of the writeList() statements within a single try statement and associate multiple handlers with it. The following listing uses one try statement for the entire method because 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 is said to govern the statements enclosed within it and defines the scope of any exceptions handlers (established by subsequent catch blocks) associated with it. In other words, if an exception occurs within the try statement, that exception is handled by the appropriate exception handler associated with this try statement.

A try statement must be accompanied either by one or more catch blocks, or one finally block.


Previous | Next | Trail Map | Writing Java Programs | Handling Errors using Exceptions