|Table of Contents|
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 ExceptionsIf you have done any amount of Java programming at all, you have undoubtedly seen an error message similar to this one: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.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); ^
Java's Catch or Specify RequirementJava requires that your programs either catch or specify all checked exceptions that can be thrown within the scope of that method.
Dealing with ExceptionsThis 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 ExceptionsThe 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
throwstatement. 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 ControversyBecause 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
finallyblock, which allows programs to cleanup after the
tryblock. See The finally Block for more information about how to use the
|Table of Contents|