Java Reference
In-Depth Information
Throwing an Exception
A Java exception is not something that is always thrown by the runtime. You can also throw an exception in your code
using a throw statement. The syntax for a throw statement is
throw <<A throwable object reference>>;
Here, throw is a keyword, which is followed by a reference to a throwable object. A throwable object is an instance
of a class, which is a subclass of the Throwable class, or the Throwable class itself. The following is an example of a
throw statement, which throws an IOException :
// Create an object of IOException
IOException e1 = new IOException("File not found");
// Throw the IOException
throw e1;
Recall that the new operator returns the reference of the new object. You can also create a throwable object and
throw it in one statement.
// Throw an IOException
throw new IOException("File not found");
The same rules for handling exceptions apply when you throw an exception in your code. If you throw a checked
exception, you must handle it by placing the code in a try-catch block, or by using a throws clause in the method or
constructor declaration that contains the throw statement. These rules do not apply if you throw an unchecked exception.
Creating an Exception Class
You can also create your own exception classes. They must extend (or inherit from) an existing exception class. I will
cover how to extend a class in detail in Chapter 16 on inheritance. This section will discuss the necessary syntax to
extend a class. The keyword extends is used to extend a class.
<<Class Modifiers>>class <<Class Name>> extends <<Superclass Name>> {
// Body for <<Class Name>>goes here
}
Here, <<Class Name>>i s your exception class name and <<Superclass Name>>i s an existing exception class
name, which is extended by your class.
Suppose you want to create a MyException class , which extends the java.lang.Exception class. The syntax
would be as follows:
public class MyException extends Exception {
// Body for MyException class goes here
}
How does the body of an exception class look? An exception class is like any other classes in Java. Typically, you
do not add any methods to your exception class. Many useful methods that can be used to query an exception object's
state are declared in the Throwable class and you can use them without re-declaring them. Typically, you include four
constructors to your exception class. All constructors will call the corresponding constructor of its superclass using
the super keyword. Listing 9-8 shows the code for a MyException class with four constructors.
 
Search WWH ::




Custom Search