import javax.swing.*; import java.awt.*; import javax.swing.event.*; import java.awt.event.*; public class ExceptionDemo extends JFrame { // inherit JFrame private JButton button1 = new JButton("Let Java handle it"); // declare and create a button private JButton button2 = new JButton("Catch it"); // declare and create a button int theArray[] = new int[10]; // create an integer array /** * Constructor sets up the window and creates a toolbar */ public ExceptionDemo() { // // setup the frames banner/title bar // super("Exception Demo : array out of bound"); // call JFrame's constructor and give it a title setSize(300,200); // set the width of the window to 300 pixels, height to 200. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // exit the whole program when this frame is closed // // Add the buttons to the frame's content pane, for each button, create a // separate inner class object as a listener and tell the button about it. // getContentPane().add("West",button1); // add button 1 button1.addActionListener(new Button1Listener()); // create its listener and tell it getContentPane().add("Center",button2); button2.addActionListener(new Button2Listener()); } /** * Inner class to handle button 1 */ class Button1Listener implements ActionListener{ public void actionPerformed(ActionEvent event) { System.out.println("We are intentionally creating an ArrayIndexOutofBoundsException"); System.out.println("The exception is not caught, instead, this is what JAVA gives you!"); theArray[11] = 42; // index beyond the array } } /** * Inner class to handle button 2 */ class Button2Listener implements ActionListener{ public void actionPerformed(ActionEvent event) { System.out.println("We are intentionally creating an ArrayIndexOutofBoundsException"); System.out.println("The exception is caught, and a message box popped up"); try{ theArray[11] = 42; // index beyond the array } catch (ArrayIndexOutOfBoundsException e) { JOptionPane.showMessageDialog(ExceptionDemo.this,"Bad index for theArray", "ArrayIndexOutOfBoundException",JOptionPane.ERROR_MESSAGE); // popup an error message } } } /*********************************************************************** * * Main routine, Note, this routine can be in any class. */ public static void main(String[] arguments){ ExceptionDemo fr = new ExceptionDemo(); // create the frame fr.setVisible(true); // allow it to be seen } }