7.1.1 Handling Exceptions

When writing a program, you can anticipate on an exception by using clauses with the keywords try and catch. In the try-clause, you specify the statements that might throw an exception, while in the catch-clause you tell what to do if something goes wrong.

In the next applet, we adapt the above applet by catching the exceptions and sending them to an extra text area.

  public boolean action (Event evt, Object arg) {
    if (evt.target == aField || evt.target == bField) {
      try {
        a = Integer.parseInt(aField.getText());
        b = Integer.parseInt(bField.getText());
        output = a/b;
        outputField.setText(String.valueOf(output));
        exceptionArea.setText("");
      }
      catch (Exception e) {
        outputField.setText("");
        exceptionArea.setText(e.toString());
      }
    }
    return true;
  }