Handling Exceptions


The Throwable Class Hierarchy

The Throwable class is the daddy of all exceptions. Figure 15-1 illustrates the Throwable class hierarchy.

image from book
Figure 15-1: Throwable Class Hierarchy

Referring to figure 15-1 — the Throwable class extends Object as expected. Throwable has two direct subclasses: Error and Exception.

There are several types of Error subclasses and many types of Exception subclasses. Errors and Exceptions are each treated differently by the Java Virtual Machine and by programmers as you will soon learn. The RuntimeException class, and its subclasses, is also given special treatment of which you must be aware. Errors, Exceptions, and RuntimeExceptions are discussed in greater detail below.

Errors

Errors are thrown by the Java Virtual Machine in the event of a non-recoverable failure. The Java API documentation specifies that “An Error ... indicates serious problems that a reasonable application should not try to catch.”

Essentially, error conditions can occur at any time for reasons beyond the normal control of a programmer. What this means to you is that any method, of any class, at any time during its execution, might possibly throw an Error! Don’t bother trying to catch them.

Exceptions

Exceptions are the opposite of Errors in that a reasonable application — meaning all the applications you write — will want to plan for them to occur and handle them properly in the source code. In fact, the Java compiler will ensure you address the possibility of an Exception being thrown by signaling a compiler error in cases where you have not done so. (See Checked vs. Unchecked Exceptions below.)

Generally speaking, you must explicitly address the possibility of a thrown Exception in your code unless the Exception is a RuntimeException.

RuntimeExceptions

A RuntimeException represents a condition that may occur during the normal execution of the Java Virtual Machine. It is a direct subclass of Exception and it and its subclasses are given special treatment. Specifically, you do not have to explicitly handle the possibility of a thrown RuntimeException in your code. Take for example the NumberFormatException whose class inheritance hierarchy is shown in figure 15-2.

image from book

 java.lang.Object  |-java.lang.Throwable     |-java.lang.Exception        |-java.lang.RuntimeException           |-java.lang.IllegalArgumentException              |-java.lang.NumberFormatException

image from book

Figure 15-2: NumberFormatException Class Inheritance Hierarchy

Referring to figure 15-2 — NumberFormatException is a subclass of IllegalArgumentException, which in turn is a subclass of RuntimeException. The NumberFormatException is declared to be thrown by the Integer.parseInt() method. You have seen the Integer class, and its parseInt() method, used in code examples of previous chapters. Example 15.1 gives a short example to refresh your memory.

Example 15.1: RuntimeExceptionTestApp.java

image from book
 1     public class RuntimeExceptionTestApp { 2        public static void main(String[] args){ 3          int i = Integer.parseInt(args[0]); 4          System.out.println("The number entered was: " + i); 5        } 6     }
image from book

In this short example the Integer.parseInt() method is used to parse a String entered via the command line and convert it into an integer. If the conversion is successful, the integer value is assigned to the variable i and its value is printed to the console. Notice the absence of a try/catch block — it’s not required since NumberFormatException is a RuntimeException. Figure 15-2 shows the results of running example 15.1 with good and bad input strings.

Referring to figure 15-3 — the application is run first with the character string “234” and again with the string “6”. Both times the application executes fine, converting the input string to an integer and printing the value. On the third run the character ‘g’ is entered on the command line and the program throws a NumberFormatException as is shown by the resulting stack trace printout. The program was ran a fourth time with no string input. This resulted in another type of RuntimeException being thrown — ArrayIndexOutOfBoundsException.

image from book
Figure 15-3: Results of Running Example 15.1 with Good and Bad Input Strings

As you can see from this short example RuntimeExceptions are given special treatment by the Java Virtual Machine.

But, just because you don’t need to catch RuntimeExceptions doesn’t mean you should never catch them or ignore them willy-nilly. The prudent programmer must make every effort to recover gracefully from program anomalies whether they are the result of bad user input or some other cause.

Checked vs. Unchecked Exceptions

Exceptions that extend from the Exception class, and are not RuntimeExceptions, are expected to be dealt with explicitly in the code by the programmer. These are referred to as checked exceptions because the Java compiler will ensure the Exception is being handled in some manner.

Errors and RuntimeExceptions do not need to be explicitly handled by the programmer and are therefore referred to as unchecked exceptions.

Quick Review

Errors and Exceptions are thrown by the Java Virtual Machine to indicate or signal the occurrence of an exceptional (abnormal) condition. The Throwable class is the root of all Errors and Exceptions.

Errors are thrown when a serious condition exists from which recovery is not possible. Errors are not handled by the programmer since they can potentially happen at any time under circumstances beyond their control.

Exceptions must be handled explicitly by the programmer unless the Exception is a RuntimeException. RuntimeExceptions can occur during the normal execution of the Java Virtual Machine. Although RuntimeExceptions can generally be ignored, the prudent programmer should give careful thought to their occurrence and handle them accordingly.

Classes that extend Exception are referred to as checked exceptions. The Java compiler will signal your failure to properly handle a checked exception. RuntimeExceptions and Errors are referred to as unchecked exceptions because programmers are not explicitly required to catch and handle them in their code.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

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