The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail Search

Trail: Essential Java Classes

Lesson: Handling Errors with Exceptions

If there's a golden rule of programming it's this: Errors occur in software programs. This we know. But what really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die?

What's an Exception and Why Do I Care?

The Java language uses exceptions to provide error-handling capabilities for its programs. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Your First Encounter with Java Exceptions

If you have done any amount of Java programming at all, you have undoubtedly already encountered exceptions. Your first encounter with Java exceptions was probably in the form of an error message from the compiler like this one:
InputFile.java:11: Exception java.io.FileNotFoundException
must be caught, or it must be declared in the throws clause
of this method.
        in = new FileReader(filename);
             ^
This message indicates that the compiler found an exception that is not being handled. The Java language requires that a method either catch all "checked" exceptions (those that are checked by the runtime system) or specify that it can throw that type of exception.

Java's Catch or Specify Requirement

This section discusses the reasoning behind this requirement and what it means to you and your Java programs.

Dealing with Exceptions

This section features an example program that can throw two different kinds of exceptions. Using this program, you can learn how to catch an exception and handle it and, alternatively, how to specify that your method can throw it.

Throwing Exceptions

The Java runtime system and many classes from Java packages throw exceptions under some circumstances by using the throw statement. You can use the same mechanism to throw exceptions in your Java programs. This section shows you how to throw exceptions from your Java code.

Runtime Exceptions--The Controversy

Although Java requires that methods catch or specify checked exceptions, they do not have to catch or specify runtime exceptions, that is, exceptions that occur within the Java runtime system. Because catching or specifying an exception is extra work, programmers may be tempted to write code that throws only runtime exceptions and therefore doesn't have to catch or specify them. This is "exception abuse" and is not recommended. The last section in this lesson, explains why.

Note to C++ Programmers:  Java exception handlers can have a finally block, which allows programs to clean up after the try block. See The finally Block for information about how to use finally.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail Search