The Java TM Tutorial

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

Trail: Essential Java Classes
Lesson: Handling Errors with Exceptions

## Catching and Handling Exceptions

> Now that you've familiarized yourself with the `ListOfNumbers` class and where the exceptions can be thrown within it, you can learn how to write exception handlers to catch and handle those exceptions.

> The three sections that follow cover the three components of an exception handler -- the `try`, `catch`, and `finally` blocks. They show you how to write an exception handler for the `ListOfNumbers` class's `writeList` method, described in The ListOfNumbers Example. Next, you'll walk through the resulting `writeList` method and see what occurs within the example code during various scenarios.

### The `try` Block

> The first step in writing an exception handler is to enclose the statements that might throw an exception within a `try` block. The `try` block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent `catch` blocks) associated with it.

### The `catch` Block(s)

> Next, you associate exception handlers with a `try` block by providing one or more `catch` blocks directly after the `try` block.

### The `finally` Block

> Java's `finally` block provides a mechanism that allows your method to clean up after itself regardless of what happens within the `try` block. Use the `finally` block to close files or release other system resources.

### Putting It All Together

> The previous sections describe how to construct the `try`, `catch`, and `finally` code blocks for the `writeList` example. Now, let's walk through the code and investigate what happens during three scenarios.

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