6.6 Writing Exceptions

 < Day Day Up > 



6.6 Writing Exceptions

In order to design an effective error-handling strategy, the implementer of a component must be able to implement his own exceptions. In order to do this, knowledge of how to create and implement Java exceptions is necessary. This section goes through the steps of creating and implementing an exception. Section 6.6.1 explains how to create a new exception, Section 6.6.2 shows how to advertise the exception to let other classes know it will be thrown, and Section 6.6.3 shows how to throw this exception at runtime.

6.6.1 Writing the Exception Class

To create a new exception, all that a programmer has to do is create a class that extends Exception. This class can now be used as an exception. However, if this is all that is done, then when the programmer later tries to call getMessage to find out something about the exception, no message will have been set and a null string results. Therefore, it always best to define two constructors: a default constructor that takes no parameters and does not set the exception message and a constructor that takes a String of the message as a parameter. Also, a programmer will often want to define special information that will be available with the exception. For example suppose the programmer would like to create an exception for when a user types in a number that is out of range of the expected values. A NumberOutOfBoundsException can be created for this exception. Associated with this exception is a variable Number, which is the actual number that was entered. This Number would be stored as part of the exception and set when the exception is created. Because this Number would be immutable, it will be set only in the constructor and a method to retrieve its value defined so that users of the exception have access to it. The NumberOutOfBoundsException is shown in Exhibit 16 (Program6.11a). Note the four constructors with this exception, one for each of the four possible ways in which the exception could be created. Once the exception class has been created, any methods that use it must advertise that they are using it.

Exhibit 16: Program6.11a: Creating a User-Defined Exception

start example

 public class NumberOutOfBoundsException extends Exception {   private int number;   public NumberOutOfBoundsException() {     number = 0;   }   public NumberOutOfBoundsException(String Message) {     super(Message);   }   public NumberOutOfBoundsException(int number) {     this.number = number;   }   public NumberOutOfBoundsException(String Message, int number)       {     super(Message);     this.number = number;   }   public int getNumber() {     return number;   } } 

end example

6.6.2 Advertise the Exception

Because the exception that is created extends Exception, it is a checked exception. This means that to use it the exception must be advertised so that the calling method knows it is responsible for handling it. An exception is advertised by using the throws clause in the method signature. This is shown in the getNumber method of Exhibit 17 (Program6.11b). Note that a program does not have to actually throw the exception to advertise it in the throws clause. A programmer could put a throws clause for an exception in the signature in order to reserve the right of this method to throw the exception if it chooses. This is particularly useful in interfaces, where an exception could be thrown by some objects that are instances of that object and not by others.

Exhibit 17: Program6.11b: Using the NumberOutOfBoundsException

start example

 import java.io.*; public class NumberTest {   public int getNumber() throws NumberOutOfBoundsException {     int number = 0;     try {       StreamTokenizer st = new StreamTokenizer(             new BufferedReader(             new InputStreamReader(System.in)));       st.nextToken();       number = (int)st.nval;       if (! (number > 0 && number < 100))         throw new NumberOutOfBoundsException(           "Invalid Number," number);     } catch (IOException e) {       e.printStackTrace();     }     return number;   }   public static void main(String args[]) {     NumberTest nt = new NumberTest();     int number = 0;     while(true) {       try {         System.out.println("Enter a number from 1 to 100");         number = nt.getNumber();         break;       } catch(NumberOutOfBoundsException e) {        System.out.println("Invalid Number" + e.getNumber() +          " try again\n");       }     }     System.out.println("number ="+ number);   } } 

end example

6.6.3 Throw the Exception

Once the exception has been created and advertised, the program needs to throw it when it occurs. Creating a new instance of the object and using the throw statement does this. Exhibit 17 (Program6.11b) illustrates a complete method that advertises and throws an exception, as well as the main program that handles the exception. This is all there is to creating and using programmer-defined exceptions. These exceptions behave exactly as exceptions that are built into the Java API because they are implemented in the same way as exceptions in the Java API. This is nice because classes that are defined by programmers do not have to have a second-class status with respect to their implementation of exception handling.



 < Day Day Up > 



Creating Components. Object Oriented, Concurrent, and Distributed Computing in Java
The .NET Developers Guide to Directory Services Programming
ISBN: 849314992
EAN: 2147483647
Year: 2003
Pages: 162

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