/* * ExceptionsDemo1.java - demonstration of throwing and catching exceptions * * This program asks the user to enter a number, the outputs its square root. * It handles appropriately two kinds of invalid data - input that is not a  * number at all, and input that is negative * * Copyright (c) 2000, 2004, 2008 - Russell C. Bjork * */ import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ExceptionsDemo1 extends JFrame implements ActionListener{    /** Main method for the program     */    public static void main(String [] args)    {        new ExceptionsDemo1().setVisible(true);    }        /** Constructor - create the GUI      */        public ExceptionsDemo1()    {        getContentPane().setLayout(new GridBagLayout());        GridBagConstraints constraints = new GridBagConstraints(            0, GridBagConstraints.RELATIVE, 1, 1, 0, 0,            GridBagConstraints.CENTER, GridBagConstraints.NONE,            new Insets(10, 10, 10, 10), 0, 0);        numberPrompt = new JLabel("Please enter a positive number");        getContentPane().add(numberPrompt, constraints);                numberInput = new JTextField(20);        getContentPane().add(numberInput, constraints);                computeButton = new JButton("Compute square root");        getContentPane().add(computeButton, constraints);                result = new JLabel(" ");        getContentPane().add(result, constraints);                // Prepare to handle mouse click on the compute button, or return        // in the text field                numberInput.addActionListener(this);        computeButton.addActionListener(this);                pack();    }          /** Method invoked when the user clicks the compute button */        public void actionPerformed(ActionEvent e)    {        // Get the number the user typed:                String numberTyped = numberInput.getText();                // Convert it to a double                double value;                try        {            value = Double.parseDouble(numberTyped);            if (value < 0)                 throw new ArithmeticException();	        double sqrt = Math.sqrt(value);     	   	result.setText("Square root is " + sqrt);        	result.setForeground(Color.black);        }        catch(NumberFormatException exception)        {            result.setText("Please enter a number");            result.setForeground(Color.red);            return;        }        catch(ArithmeticException exception)        {            result.setText("Not a real number");            result.setForeground(Color.red);            return;        }    }          // Instance variables - components of the GUI        private JLabel numberPrompt;    private JTextField numberInput;    private JButton computeButton;    private JLabel result;}