ExceptionDemo.java

Download ExceptionDemo.java

Show with line numbers

// This code demonstrates catching and also throwing exceptions.
// In real code, reusable modules that detect errors can't know what
// to do about them, while the application that uses those modules
// knows what to do, but can't easily detect errors.  So reusable
// modules often throw exceptions and applications/applets catch them.
//
// In this class, no "checked" exceptions are used, so no try-catch block
// is actually required.  (Should an Exception occur, the JRE uses a default
// handler that prints the exception and a stack trace to the console.)  If
// the "inverse" method threw a checked exception than it would need to be
// declared with a "throws" clause, something similar to this:
//      float inverse ( float num ) throws WhatEverException
//
// You can find a list of standard Exceptions in java.lang (and other)
// packages, in the JavaDocs.
//
// Written 3/2006 by Wayne Pollock, Tampa Florida USA.

import javax.swing.JOptionPane;

class ExceptionDemo
{
   public static void main ( String [] args )
   {
      int num = 0;
      String input = JOptionPane.showInputDialog( "Enter a number:" );
      try
      {
         num = Integer.parseInt( input );
         System.out.println( "The inverse of " + num + " is " + inverse(num) );
      }
      catch ( NumberFormatException e )
      {
         System.out.println( "\"" + input + "\" is not a number!" );
      }
      // Comment out the following catch clause, run with "0" (zero), and
      // see the default error handler output.
      catch ( IllegalArgumentException e )
      {
         System.out.println( e.getMessage() );
      }
   }

   static float inverse ( float num )  // throws IllegalArgumentException
   {
      if ( num == 0.0f )
         throw new IllegalArgumentException( "num must not be zero!" );

      return 1 / num;
   }
}