Previous | Next | Trail Map | Writing Java Programs | Table of Contents


Handling Errors using Exceptions

If there's one 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?

The Java language uses exceptions to provide error handling capabilities for its programs. In this lesson you will learn what an exception is, how to throw and catch exceptions, what to do with an exception once you've caught it, and how to best use the exception class hierarchy provided by the Java development environment.

What's an Exception and Why Do I Care?

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 seen an error message similar to this one:
InputFile.java:9: Exception java.io.FileNotFoundException must be caught, or it must be declared in the throws clause of this method.
        fis = new FileInputStream(filename);
              ^
This message indicates that the compiler found an exception that is not being dealt with. The Java language requires that all "checked" exceptions be caught or specified. Checked exceptions are those exceptions that are not runtime exceptions.

Java's Catch or Specify Requirement

Java requires that your programs either catch or specify all checked exceptions that can be thrown within the scope of that method.

Dealing with Exceptions

This section features an example program which can throw two different exceptions. Using this example program, you will learn how to catch an exception and handle it, and alternatively, how to specify an exception.

Throwing Exceptions

The Java runtime system and the some of the classes from the Java packages all throw exceptions under some circumstances. You can use the same mechanism to throw exceptions in your Java programs. This section shows you how you can throw exceptions from your own Java code using the throw statement. All exceptions must be Throwable. That is, exceptions must inherit (either directly or indirectly) from the Throwable class defined in the java.lang package.

Runtime Exceptions--The Controversy

Because the Java language does not require methods to catch or specify runtime exceptions, it's tempting for programmers to write code that throws only runtime exceptions. This is "exception abuse" and is not recommended.

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


Previous | Next | Trail Map | Writing Java Programs | Table of Contents