Summary


Creating Custom Exceptions

You can easily create custom exceptions by extending any of the Throwable classes. For most situations you will extend the Exception class. In this case you would be creating a checked exception. You may discover a need to extend the RuntimeException class in which case you would be creating an unchecked exception, but a need to do this does not normally present itself. You would most certainly never find a need to extend the Error class unless perhaps you were writing your own custom Java Virtual Machine.

In this section I will show you how to extend the functionality of the Exception class to create your own custom exceptions. Here you’ll learn how to use the throw keyword to explicitly throw an exception, how to translate low-level exceptions into higher level exception abstractions, how to chain exceptions, and how to set and get an exception’s cause field.

High & Low Level Abstractions

The Java Platform API provides many types of exceptions that represent the range of exceptional conditions that can occur through the use of various API class methods. These exception abstractions are appropriate for the Java Platform API. However, if you are creating your own set of custom classes the exception abstractions provided by the Java API may be too low level to sufficiently represent the abstraction(s) you have in mind. When this situation arises you can create your own custom exceptions.

Extending The Exception Class

To create a custom exception you can extend the Exception class and add any functionality you require including additional fields and methods. Normally, however, you are well served by simply utilizing the functionality provided by the Exception class. Examples 15.10 and 15.11 demonstrate the use of a custom exception. Example 15.10 gives a class named CustomException that has four constructor methods, one for each type of constructor offered in the Exception class. Example 15.11 gives a modified version of the ClassLoaderTestApp program.

Example 15.10: CustomException.java

image from book
 1     public class CustomException extends Exception { 2       public CustomException(String message, Throwable cause){ 3          super(message, cause); 4       } 5     6       public CustomException(String message){ 7           super(message); 8       } 9 10      public CustomException(){ 11       super("Custom Exception"); 12      } 13 14      public CustomException(Throwable cause){ 15        super(cause); 16      } 17    }
image from book

Example 15.11: ClassLoaderTestApp.java (Mod I)

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

Referring to example 15.11 — several important modifications were made to this program to demonstrate the use of the CustomException. First, the offending code in the loadClass() method is now enclosed in a try block. The try block is followed by three catch blocks to handle each type of exception that might be thrown when the code executes. Each catch block catches its particular exception and chains it to a new CustomException with a customized message. The newly created CustomException is thrown with the throw keyword.

The main() method code is now mostly concerned with catching CustomExceptions. However, no loss of information occurs because you can get the low level cause of the exception in addition to its message. Figure 15-9 shows the results of running this program.

image from book
Figure 15-9: Results of Running Example 15.11

Referring to figure 15-9 — the ClassLoaderTestApp program is run first without an argument naming a class to dynamically load. This results in the expected error message being printed to the console. The second time around it is run with the string “CustomException”. This causes the CustomException class to be dynamically loaded and its information printed to the console. The third time the program runs it’s given the string “java.lang.Object” and, as expected, an Object is dynamically loaded and its information is printed to the console.

Some Advice On Naming Your Custom Exceptions

In this section I am completely guilty of asking you to do as I say but not as I just did! In the previous example I used the name CustomException for the sake of simplicity. In practice you will want to choose the names of your exception abstractions as carefully as you choose any of your abstraction names. This you must do to preserve the clarity of your program.

Quick Review

Create custom exceptions by extending the Exception class. Choose the names of your exception abstractions as carefully as you choose other program abstraction names.

You can chain low level exceptions to higher level exception abstractions by catching the low level abstraction in a catch block and using it as a cause argument for a custom exception. You can gain access to an exception’s cause via the Throwable.getCause() method.




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