The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search

Trail: Essential Java Classes
Lesson: Handling Errors with 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 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.

> >     PrintWriter out = null;

> >     try {
> >         System.out.println("Entering try statement");
> >         out = new PrintWriter(
> >                   new FileWriter("OutFile.txt"));

> >         for (int i = 0; i < size; i++)
> >             out.println("Value at: " + i + " = " + victor.elementAt(i));
> >     }

> The `try` statement governs the statements enclosed within it and defines the scope of any exception handlers 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 by at least one `catch` block or one `finally` block.

| Start of Tutorial > Start of Trail > Start of Lesson | Search