Start of Tutorial > Start of Trail |
Search
Feedback Form |
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?
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.
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: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.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 section discusses the reasoning behind this requirement and what it means to you and your Java programs.
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.
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.
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 afinally
block, which allows programs to clean up after thetry
block. See Thefinally
Block for information about how to usefinally
.
Start of Tutorial > Start of Trail |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.