The JavaTM Tutorial

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

Trail: Learning the Java Language
Lesson: Language Basics

## Exception Handling Statements

> The Java programming language provides a mechanism known as exceptions to help programs report and handle errors.

> To indicate that an error has occurred within a program, use the throw statement. The general form of the `throw` statement looks like this:

> >     throw exception;

> exception is an object that inherits either directly or indirectly from the `Exception` class. The exception object's class indicates the type of error. The exception object contains a detailed message about the error, information about where the error occured, and possibly other details about the error.

> The `throw` statement interrupts the normal flow of the program and attempts to find an exception handler for the type of exception that was thrown. An exception handler is a block of code that can handle a particular type of error, either by recovering from it or by determining that the error is unrecoverable and attempting to provide a gentle exit from the program.

> Three statements play a part in handling exceptions:

> - The try statement identifies a block of statements within which an exception might be thrown.
> - The catch statement must be associated with a `try` statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the `try` block.
> - The finally statement must be associated with `try` statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the `try` block.

> Here's the general form of these statements:

> >     try {
> >         statements
> >     } catch (exceptiontype name) {
> >         statements
> >     } catch (exceptiontype name) {
> >         statements
> >     } finally {
> >         statements
> >     }

> Notice that more than one `catch` statement can be associated with a `try` statement. Furthermore, a `try` statement must have at least one `catch` or `finally` statement associated with it.

> This has been a brief overview of the statements provided by the Java programming language used in reporting and handling errors. However, other factors and considerations, such as the difference between runtime and checked exceptions and the hierarchy of exceptions classes, play a role in using Java's exception mechanism. The Handling Errors with Exceptions lesson provides a complete discussion on this subject.

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