Exceptions

Defining new exceptions

DivideByZeroException.java

Definition of class DivideByZeroException.
Used to throw an exception when a
divide-by-zero is attempted.

public class DivideByZeroException
             extends ArithmeticException {
   public DivideByZeroException()
   {
      super( "Attempted to divide by zero" );
   }

   public DivideByZeroException( String message )
   {
      super( message );
   }
}

DivideByZeroTest.java

A simple exception handling example.
Checking for a divide-by-zero-error.

import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DivideByZeroTest extends JFrame
                              implements ActionListener {
   private JTextField input1, input2, output;
   private int number1, number2;
   private double result;

   // Initialization
   public DivideByZeroTest()
   {
      super( "Demonstrating Exceptions" );

      Container c = getContentPane();
      c.setLayout( new GridLayout( 3, 2 ) );

      c.add( new JLabel( "Enter numerator ",
                         SwingConstants.RIGHT ) );
      input1 = new JTextField( 10 );
      c.add( input1 );

      c.add(
         new JLabel( "Enter denominator and press Enter ",
                     SwingConstants.RIGHT ) );
      input2 = new JTextField( 10 );
      c.add( input2 );
      input2.addActionListener( this );

      c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
      output = new JTextField();
      c.add( output );

      setSize( 425, 100 );
      show();
   }

   // Process GUI events
   public void actionPerformed( ActionEvent e )
   {
      DecimalFormat precision3 = new DecimalFormat( "0.000" );

      output.setText( "" ); // empty the output JTextField

      try {         
         number1 = Integer.parseInt( input1.getText() );
         number2 = Integer.parseInt( input2.getText() );

         result = quotient( number1, number2 );
         output.setText( precision3.format( result ) );
      }
      catch ( NumberFormatException nfe ) {
         JOptionPane.showMessageDialog( this,
            "You must enter two integers",
            "Invalid Number Format",
            JOptionPane.ERROR_MESSAGE );
      }
      catch ( DivideByZeroException dbze ) {
         JOptionPane.showMessageDialog( this, dbze.toString(),
            "Attempted to Divide by Zero",
            JOptionPane.ERROR_MESSAGE );
      }
   }

   // Definition of method quotient. Used to demonstrate
   // throwing an exception when a divide-by-zero error
   // is encountered.
   public double quotient( int numerator, int denominator )
      throws DivideByZeroException
   {
      if ( denominator == 0 )
         throw new DivideByZeroException();

      return ( double ) numerator / denominator;
   }

   public static void main( String args[] )
   {
      DivideByZeroTest app = new DivideByZeroTest();

      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               e.getWindow().dispose();
               System.exit( 0 );
            }
         }
      );
   }
}

try - catch - finally

The programmer encloses in a try block the code that may generate an error that will produce an exception. The try block is immediately followed by one or more catch blocks. Each catch block specifies the type of exception it can catch and handle.

If no exceptions are thrown in the try block, the exception handlers for that block are skipped and the program resumes execution after the last catch block, after executing a finally block if one is provided.

D:\cps592\ch14\fig14_08>java UsingExceptions1
Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException

UsingExceptions1.java

public class UsingExceptions1 {
   public static void main( String args[] )
   {
      try {
         throwException();
      }
      catch ( Exception e )
      {
         System.err.println( "Exception handled in main" );
      }

      doesNotThrowException();
   }

   public static void throwException() throws Exception
   {
      // Throw an exception and immediately catch it.
      try {
         System.out.println( "Method throwException" );
         throw new Exception();  // generate exception
      }
      catch( Exception e )
      {
         System.err.println(
            "Exception handled in method throwException" );
         throw e;  // rethrow e for further processing

         // any code here would not be reached
      }
      finally {
         System.err.println(
            "Finally executed in throwException" );
      }

      // any code here would not be reached
   }

   public static void doesNotThrowException()
   {
      try {
         System.out.println( "Method doesNotThrowException" );
      }
      catch( Exception e )
      {
         System.err.println( e.toString() );
      }
      finally {
         System.err.println(
            "Finally executed in doesNotThrowException" );
      }

      System.out.println(
         "End of method doesNotThrowException" );
   }
}

Stack Unwinding

D:\cps592\ch14\fig14_09>java UsingExceptions2
Method throwException
Finally is always executed
Exception handled in main

UsingExceptions2.java

public class UsingExceptions2 {
   public static void main( String args[] )
   {
      try {
         throwException();
      }
      catch ( Exception e ) {
         System.err.println( "Exception handled in main" );
      }
   }

   public static void throwException() throws Exception
   {
      // Throw an exception and catch it in main.
      try {
         System.out.println( "Method throwException" );
         throw new Exception();      // generate exception
      }
      catch( RuntimeException e ) {  // nothing caught here
         System.err.println( "Exception handled in " +
                             "method throwException" );
      }
      finally {
         System.err.println( "Finally is always executed" );
      }
   }   
}

getMessage and printStackTrace methods

D:\cps592\ch14\fig14_10>java UsingExceptions3
Exception thrown in method3

java.lang.Exception: Exception thrown in method3
        at UsingExceptions3.method3(UsingExceptions3.java:28)
        at UsingExceptions3.method2(UsingExceptions3.java:23)
        at UsingExceptions3.method1(UsingExceptions3.java:18)
        at UsingExceptions3.main(UsingExceptions3.java:8)

UsingExceptions3.java

Demonstrating the getMessage and printStackTrace
methods inherited into all exception classes.

public class UsingExceptions3 {
   public static void main( String args[] )
   {
      try {
         method1();
      }
      catch ( Exception e ) {
         System.err.println( e.getMessage() + "\n" );
         e.printStackTrace();
      }
   }

   public static void method1() throws Exception
   {
      method2();
   }

   public static void method2() throws Exception
   {
      method3();
   }

   public static void method3() throws Exception
   {
      throw new Exception( "Exception thrown in method3" );
   }
}

Notes

The operand of a throw can be of any class derived by Throwable. The immediate subclasses of Throwable are Exception and Error.

Errors are particularly serious system problems that generally should not be caught. Exceptions are caused by problems most Java programs should be able to deal with, such as invalid input or data strings.


Maintained by John Loomis, last updated 22 June 2000