Types of Exceptions
An exception is always an object of some subclass of the standard class Throwable. Two direct subclasses of the class Throwable the class Error and the class Exception cover all the standard exceptions. Both these classes themselves have subclasses that identify specific exception conditions.
The exceptions that are defined by the Error class and its subclasses are characterized by the fact that they all represent conditions that you aren’t expected to do anything about, so you aren’t expected to catch them. Error has three direct subclasses—ThreadDeath, LinkageError, and VirtualMachineError.
For almost all the exceptions that are represented by subclasses of the Exception class, you must include code in your programs to deal with them if your code may cause them to be thrown. If a method in your program has the potential to generate an exception of a type that has Exception as a superclass, you must either handle the exception within the method or register that your method may throw such an exception. If you don’t, your program will not compile.
Dealing with Exceptions
Whenever you write code that can throw an exception, you have a choice. You can supply code within the method to deal with any exception that is thrown, or you can essentially ignore it by enabling the method containing the exception throwing code to pass it on to the code that called the method.
To declare that your method can throw exceptions you just put the throws keyword after the parameter list for the method.
double myMethod() throws IOException {
// Detail of the method code...
}
If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them try, catch, and finally blocks.
- A try block encloses code that may give rise to one or more exceptions. Code that can throw anexception that you want to catch must be in a try block.
- A catch block encloses code that is intended to handle exceptions of a particular type that maybe thrown in the associated try block. I’ll get to how a catch block is associated with a tryblock in a moment.
- The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
try {
// Code that can throw one or more exceptions
} catch(Exception e) {
// Code to handle the exception
} finally {
// Clean-up code to be executed last
}
To demonstrate the use of Exceptions and how can you create your own I created a quick example. Click here to download the code.
No comments:
Post a Comment