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


Handling Errors Using Exceptions (1.1notes)

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. So:

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 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 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 inherit (either directly or indirectly) from the Throwable class defined in the java.lang package.

Runtime Exceptions--The Controversy

As mentioned previously, Java requires that methods catch or specify checked exceptions. However, methods do not have to catch or specify runtime exceptions, exceptions that occur within the Java runtime system. Because catching or specifying an exception is extra work, it is tempting for programmers to write code that throws only runtime exceptions, and therefore doesn't have to catch or specify exceptions. This is "exception abuse" and is not recommended. This section explains why.

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