Creating Custom Exceptions


Throwing Exceptions

In the previous section I showed you how to catch and process exceptions. In this section I will show you how to throw exceptions. You will want to throw an exception in several situations. For instance, if you don’t want to handle an exception in a particular piece of code you must indicate to someone using the method in which your code appears that it will throw an exception. In another example, you may process the exception in your code, repackage or translate the exception into a different kind of exception, and throw the new exception.

The Throws Clause

The throws clause is used in a method declaration or definition to indicate that the method in question might throw an exception of the indicated type(s). Examples 15.8 and 15.9 together demonstrate the use of the throws clause. This program takes a string input from the command line and attempts to load the class by that name, create an object of the class type, and call a method on the newly created object. This program uses the services of the java.lang.Class class. Example 15.8 is a user-defined class named ExampleClass that provides simple functionality by overriding the Object.toString() method. Example 15.9 is an application named ClassLoaderTestApp that uses the Class.forName() method to dynamically load the ExampleClass and create an object of its type.

Example 15.8: ExampleClass.java

image from book
 1     public class ExampleClass { 2        public ExampleClass(){ 3          System.out.println("ExampleClass object created!"); 4        } 5        public String toString(){ 6          return super.toString(); 7        } 8     }
image from book

Example 15.9: ClassLoaderTestApp.java

image from book
 1     public class ClassLoaderTestApp { 2 3        Object _object = null; 4 5        public void loadClass(String class_name) throws ClassNotFoundException, InstantiationException, 6                              IllegalAccessException, ArrayIndexOutOfBoundsException { 7           Class loaded_class = Class.forName(class_name); 8           _object = loaded_class.newInstance(); 9           System.out.println(_object.toString()); 10       } 11     12       public static void main(String[] args){ 13         ClassLoaderTestApp clta = new ClassLoaderTestApp(); 14         try{ 15              clta.loadClass(args[0]); 16            } 17            catch(ClassNotFoundException e){ 18              System.out.println("A class by that name does not exist. Please try again."); 19 20             } 21            catch(InstantiationException e){ 22              System.out.println("Problem creating an object of that class type. Please try again."); 23             } 24            catch(IllegalAccessException e){ 25              System.out.println(e.toString()); 26            } 27            catch(ArrayIndexOutOfBoundsException e){ 28              System.out.println("You failed to enter a string when you ran the program!" 29                              + "Please try again!"); 30            } 31       } 32    }
image from book

Referring to example 15.9 — ClassLoaderTestApp has one method named loadClass() which uses the throws clause to indicate that its execution might result in four exceptions being thrown. All the exceptions are checked exceptions except our old friend ArrayIndexOutOfBoundsException.

The loadClass() method is called in the main() method, and it’s the main method’s responsibility to handle the exceptions thrown by the loadClass() method. (Alternatively, the main() method could itself use the throws clause to pass the buck on up the calling chain.)

When this program is run an instance of ClassLoaderTestApp is created and accessed via the reference named clta. The loadClass() method is called on line 15 using the String reference located at args[0] as an argument. In the loadClass() method, an attempt is made on line 7 to load the class whose name matches that of the input string. If this line fails, a ClassNotFoundException is thrown. If the class loads fine line 8 executes, however, if there’s a problem creating an object of that class type an InstantiationException is thrown. If the object is created successfully then its string representation is printed to the console on line 9.

Figure 15-8 shows the results of running this program with valid and invalid input strings.

image from book
Figure 15-8: Results of Running Example 15.9

The throw Keyword

The throw keyword is used to explicitly throw an exception. The use of the throw keyword is discussed and demonstrated in detail in the Creating Custom Exceptions section.

Quick Review

Use the throws clause in a method declaration to indicate what type(s) of exception(s) a method might throw.




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