|
|
< Day Day Up > |
|
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.
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
Exhibit 16: Program6.11a: Creating a User-Defined Exception
|
|
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; } }
|
|
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
Exhibit 17: Program6.11b: Using the NumberOutOfBoundsException
|
|
{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}
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); } }
|
|
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
|
|
< Day Day Up > |
|