Exception Handling
- An exception
is an unexpected condition encountered by your program.
- An exception can be a fatal error or any unusual situation.
- An exception is thrown
and it is caught
when it is handled.
- When you handle an Exception, you are protecting your code
from the exception.
- The compiler will make sure your code catches all the exceptions it is required to handle.
- You protect your code with try
blocks and handle the exception with catch
blocks.
- The code in each catch block is called the exception handler.
- Exceptions are organized in a hierarchy of Exception Classes
- When an exception occurs, an object of class Error or Exception is created (or "thrown"). Theses are both subclasses of class Throwable.
- Errors and RuntimeExceptions are non-recoverable errors, and are considered "unchecked", meaning your code does not need to handle them. These includes NullPointerException, IndexOutOfBoundsException, and other programmer errors or errors the JVM encounters.
- You should NOT catch these - fix your code instead!
- Exceptions are the errors that a robust Java program should catch and handle.
- The Exception class has many subclasses corresponding the various problems that can be encountered.
- Look at the online help for the
Exception and
Error
classes in the onine Java documentation.
- Catching Exceptions
- Throwing Exceptions
- Exceptions and Style
- Example - Opening a Datafile
- Read the Java Tutorial on Exceptions - focus on the sections about what an exception is, creating exception classes, and the advantages of exceptions.