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.
You
put the code that is likely to produce an error in the try{}.
Inside
the catch() you need to put the type of error that is produced.
Inside
the catch {} you need to put the code that will be executed if an error
is encountered.
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");
}
}
}
}