by David Wood

Final Wrapup on Exceptions

This week, as promised, we're going to have a final wrapup on Exceptions. This subject has made us delve deep into a lot of theory, and we know that most people learn best by practical example, so it seems most fitting that we conclude with a real example.

The applet above is extremely simple; its purpose is to illustrate the functioning of a method that converts a string into a number. Try typing a number into the text field and hit "Convert"--an apparently identical number will appear in the display field below. The difference between the number you entered and the number that appeared is that the new number has actually been converted to a floating point variable.

A few weeks ago, when we discussed the use of parameters with applets, we first introduced the idea of exceptions by way of the fact that the Java routine for converting a string to an integer throws an exception. Specifically, it throws a NumberFormatException when the string in question can't be converted.

The applet above has implemented a simple exception handler for the NumberFormatException in our conversion (in this case, a conversion to a floating point variable). If you enter some characters other than numbers into the field, you'll notice that "Not A Number!" promptly appears in the lower box once you press Convert.

Below is the source for the applet:



import java.awt.*;
import java.applet.Applet;

public class ExceptionTest extends Applet
{
  // Objects that all methods should share:
  Button convert;
  TextField inputf,resultf;

  public void init () 
  {
    // Create and set up interface objects
    convert = new Button("Convert");
    inputf = new TextField(15);
    inputf.setEditable(true);
    resultf = new TextField(20);
    resultf.setEditable(false);

    add(convert); // "Add" them to the
    add(inputf);  // actual interface...
    add(resultf);
  }

  public boolean action (Event e,Object arg)
  {
    if (e.target == convert)
    {
      try
      {
        Float result = new Float(inputf.getText());
        resultf.setText(result.toString());
      }
      catch (NumberFormatException nfe)
      {
        resultf.setText("Not A Number!");
      }
      return true;
    }
    return false;
  }
}


This is an applet with only two methods (that we've defined). The first is its init(), which for those who've skipped the beginning lessons in applet creation, is the method that executes first (and only once) when the applet comes into being on your web page.

The only thing our init() does is to instantiate (which is, simply, to create) interface objects (which are, simply, objects that correspond to elements in your user interface). There's one for the button, one for the input field, and one for the output field. We've placed the objects themselves inside the class definition rather than inside this method because of something called scope; to place the declaration lines (such as "Button convert") inside the init() method itself would imply that the objects wouldn't exist once the method was completed.

This detail aside, the button's label is set as a parameter to its constructor (in other words, the method executed when it's new'ed), as are the lengths of the text fields. You'll also notice the setEditable() method; this, as you may have guessed, is what tells the interface whether the user may type into the TextField in question. Obviously, the upper field that allows you to type has been set as editable, while the result field below has been set as uneditable. Then the three objects are add'ed, and presto, in 10 lines of code, you have an instant interface.

Meanwhile, the action() method we've defined does the real work of the applet. If you recall from our coverage of event handling, action is a special method that is executed any time there's been an action on one of our user interface objects. Our action routine is looking to see if any particular action is related to our convert button (namely, whether it's being pressed), and, if it is, then it executes our conversion. This is accomplished, as you can see, by comparing a part of the Event object that we're passed in action() (the target part) with our actual "target" object--that is, the convert Button.

You can see our exception handler inside this if-statement. We try to construct a Float object with a string. Specifically, we try to construct our Float with the String that we can tell our editable TextField to report to us. Java's Float object has a constructor that works just like the parseInt we mentioned above, as stated before, throwing an exception on failure.

If there's no exception, then the try section completes--the result is displayed--after it's been reconverted to a String, which is the only thing that the TextField understands. If an exception does happen, our catch section kicks in. It receives the NumberFormatException object thrown by the bad conversion and then executes. In this case, it just sets the result to a (supposedly) informative message.

You may begin to see from this small example how exceptions are applied and dealt with in a variety of situations. This understanding will most likely be needed immediately for Java projects of even modest complexity.

We should offer a caveat, in conclusion: Exception handlers may not have only one catch section; as many as desired may be included (one after the other). There is, in addition, a finally clause that can be included as part of your exception handler, but this detail will be clarified in a later example.

Past installments of Java Jolt

http://www.internet.com/