Program 18.2: Throwing New Exceptions

So far you've seen a exceptions thrown by the Java runtime and API. However you can build your own exceptions into classes as well. One place you may want to do this is when you need to verify user input.

For instance suppose you have a system with which users connect to order books. One of the fields in an order form is the number of copies the user wants. You hope that the user will enter a small positive number in this box. However as anyone who's ever worked with such a system will tell you, only about half the people who use the form will do what you expect. The other half will enter "one," "two," "a few," "1.5," leave it blank or otherwise enter some value that can't be easily recognized as the number you want. To handle this you can define a new subclass of Exception called NotANaturalNumberException. Then when some two-year-old runs his fingers across your keyboard filling your fields with values like "idoaehdoeunth" you can throw a NotANaturalNumberException. The syntax for this is very simple. Here it is:

class NotANaturalNumberException extends Exception {

  public int getANaturalNumber 
    throws NotANaturalNumberException (String data) {

     int i = 0;

    try {
      i = Integer.valueOf(data).intValue();  
    if (i <= 0) throw new NotANaturalNumberException();

    return i;
getANaturalNumber begins by setting i to an invalid number, zero. Then an attempt is made to convert the data into an integer. If it succeeds i is now an integer. If the attempt fails i is still zero. In either case you then fall out of the try block and test whether i is a natural number. If it's not, i.e. if it's less than or equal to zero, then you throw a new NotANaturalNumberException. If this exception is thrown then control passes to the nearest enclosing catch block. No value is returned from the getANaturalNumber method. The NotANaturalNumberException class itself doesn't contain any code or data. It's used purely as a mnemonic for the programmer to know what problem has occurred. You can add code and data to a new exception. In this example you might want to add the data that was submitted and a toString method with an error message. Program 18.2 is a NotANaturalNumberException with polymorphic constructors and a toString method. Program 18.2: NotANaturalNumberException

public class NotANaturalNumberException extends Exception {

  String errmsg;
  public NotANaturalNumberException() {
    errmsg = "Not a Natural Number";
  public NotANaturalNumberException(String s) {
    errmsg = s + " is not a natural number";
  public String toString() {
    return errmsg;

Copyright 1996 Elliotte Rusty Harold
This Chapter