The Throwable Class and Its Subclasses


The Throwable Class and Its Subclasses

The Throwable class is the superclass of all errors and exceptions. Therefore, the JVM throws only this class or one of its subclasses. Likewise, you can supply only this type of object to the throw statement and in a catch clause.

Java distinguishes errors from exceptions by specifying that errors are not expected to be caught because they are usually unexpected and fatal. Exceptions are undesirable, but are expected and should be caught. In Java, exceptions and errors are objects. The JVM instantiates an appropriate subclass of Exception or Error to represent the problem. The Exception and Error classes, in turn , extend java.lang.Throwable . These objects indicate the type of problem and usually contain detailed information about the condition that caused the problem. Note that you don't use Throwable directly, but instead use one of its subclasses, such as Exception . The following sections explain the differences between Exception and Error objects in more detail.

Errors

An error indicates a fatal problem. Your application should not be expected to recover from an error. For example, if the system runs out of memory, the JVM crashes, which is an error. This type of condition is beyond the JVM's control, so your code cannot do much about it. When an error crashes the JVM, your application will also crash. In some cases, you do have a chance to respond ”say, display a final status message ”but in others you don't get even that chance.

The following are typical examples of errors:

  • java.awt.AWTError ” Indicates a serious Abstract Windowing Toolkit (AWT) error.

  • java.xml.parsers.FactoryConfigurationError ” Occurs when the XML parser cannot be found.

  • java.lang.LinkageError ” Usually a subclass, such as NoClassDefFoundError , is thrown when the class has been corrupted or has been changed after compiling the linking class.

  • java.lang.ThreadDeath ” Indicates that a thread died. These errors should not be caught, as having a thread die is a normal occurrence. However, a thread death is considered an error because most applications crash when this event takes place.

  • java.lang.VirtualMachineError ” Indicates a serious problem in the JVM. Running out of memory is a common example of this type of error.

Exceptions

An exception is thrown when something bad happens, but not so serious that the application crashes. You should catch all exceptions. In fact, compiling a program without doing so is difficult because the compiler usually complains if you miss an exception. However, you can catch a superclass of an exception and miss the subclass. In that case, the compiler does not complain, but your error handling is not as detailed as it should be. Also, the compiler doesn't complain for unchecked exceptions, even if they are not put in the try-catch block. The "unchecked exceptions" means that the compiler doesn't check them during compiling time.

The following are typical examples of exceptions:

  • java.awt.AWTException ” Indicates that an AWT exception has occurred.

  • java.lang.ClassNotFoundException ” Indicates that no definition for the class with the specified name could be found, probably because the name is misspelled or the class is in the wrong place.

  • java.lang.IllegalAccessException ” Occurs when an application tries to reflectively create an instance, set or get a field, or call a method, but the currently running method does not have access to that item.

  • java.lang.InstantiationException ” This exception usually occurs because of an attempt to instantiate an interface or abstract class. It is thrown when creating an instance of a class using Class.newInstance() , but the new instance can't be created because it's an interface or an abstract class.

  • java.lang.InterruptedException ” Occurs when one waiting or sleeping thread is interrupted by another thread.

  • java.io.IOException ” Usually a subclass, such as FileNotFoundException or RemoteException , is thrown by a failed or interrupted I/O operation.

  • java.lang.RuntimeException ” Usually a subclass, such as ArithmeticException , IndexOutOfBoundsException , or NullPointerException , is thrown during the JVM's normal operation. Unlike most exceptions, a method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during method execution but not caught. If you don't catch an exception the JVM must handle them which eliminates your ability to know exactly what went wrong via try-catch blocks.

  • javax.naming.NamingException ” Usually a subclass, such as InvalidNameException or NameNotFoundException , is thrown if a name does not conform to the syntax defined for the namespace.

Numerous exceptions are defined in Java, but the preceding list covers the most likely problems a program might have. However, you will probably want to write your own exception for the assignment.

Custom Throwable Subclass

Although writing your own exception class isn't mandatory, it does demonstrate a good understanding of error handling. Listing 17.1 is an example (also used in the book sample application) of how you might handle your application being unable to open a database file or an RMI connection. Modeled after FileNotFoundException , this exception is thrown by one of several methods when the database file cannot be found or RMI doesn't work ”for example, when an attempt is made to read data from the database.

Listing 17.1 An Example of a Custom Exception
 import java.io.IOException; /**  * My application couldn't open the database file or RMI  * connection.  * <p> Modeled after the <code>FileNotFoundException</code>,  * this exception will be thrown by one of several  * methods when the database file cannot be found or RMI  * doesn't work -- for example, when an attempt is made to  * read data from the database.  *  * @author  QUE reader  * @version 1.0, 2/23/04  * @since   JDK1.4  */ public class SCJDException extends IOException {     /**      * Constructs a <code>SCJDException</code> with      * a general message.      */     public SCJDException()     {        super("Cannot find Database or RMI connection.");     }     /**      * Constructs a <code>SCJDException</code> with the      * specified detail message. The string <code>s</code>      * can be retrieved later by the      * <code>{@link java.lang.Throwable#getMessage}</code>      * method of class <code>java.lang.Throwable</code>.      *      * @param   s   the detail message.      */     public SCJDException(String s)     {         super(s);     }     /**      * Constructs a <code>SCJDException</code> with a      * detail message consisting of the given pathname      * string followed by the given reason string.      *      * @param   path   the attempted path.      * @param   reason   problem description.      */     private SCJDException(String path, String reason)     {         super(path + ((reason == null)               ? ""               : " (" + reason + ")"));     } } 


JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net