Throwing Exceptions

 

When James Gosling and his team at Sun MicroSystems developed Java, they wanted to build in an error handling mechanism to force beginning programmers to handle errors well. Files are a place where things often go wrong – they go missing, they get renamed accidentally and they get modified and mess up programs. The creators of Java wanted you to deal with these situations well, ie. without crashing your entire system. Their solution was the try/catch syntax.

You have already discovered that when you have a textField the user can enter whatever they want in it. If they enter a word or a blank, you get a java.lang.NumberFormatException. If you wished, you could “catch” this error with a message.

   try
   {
     <Code that might cause an error>
   }
   catch (<Error type> e)
   {
     <Error message>;
   }

This is an example of code that attempts to access an element in an array that doesn't exist:

   int array [] = new int [8];
   for (int i = 0 ; i < array.length ; i++)
   {
     array [i] = i;
   }
   
   try
   {
     array [8] = 1;//doesn't exist
   }
   catch (java.lang.ArrayIndexOutOfBoundsException e)
   {
     System.out.println ("Array Error occurred: " + e);
   }

This is an applet example. There is an input box where the user is supposed to enter an integer, if they enter a string or letter, then an error occurs. The try/catch statement catches the error if the user enters something that will cause an error.

   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
   import java.applet.Applet;
   public class TryCatch2 extends Applet implements ActionListener
   {
     JLabel prompt;
     JTextField input;
     JButton exit;
     public void init ()
     {
       prompt = new JLabel ("Enter a number");
       input = new JTextField (20);
       exit = new JButton ("Enter");
       exit.setActionCommand ("hi");
       exit.addActionListener (this);
       add (prompt);
       add (input);
       add (exit);
     }
    public void actionPerformed (ActionEvent e)
    {
      if ("hi".equals (e.getActionCommand ()))
      {
        try
        {
          int x = Integer.parseInt (input.getText ());
        }
        catch (java.lang.NumberFormatException m)
        {
          showStatus ("Please enter an integer");
        }
      }
   }
}