ExceptionDemo.java

Download ExceptionDemo.java

 1: // This code demonstrates catching and also throwing exceptions.
 2: // In real code, reusable modules that detect errors can't know what
 3: // to do about them, while the application that uses those modules
 4: // knows what to do, but can't easily detect errors.  So reusable
 5: // modules often throw exceptions and applications/applets catch them.
 6: //
 7: // In this class, no "checked" exceptions are used, so no try-catch block
 8: // is actually required.  (Should an Exception occur, the JRE uses a default
 9: // handler that prints the exception and a stack trace to the console.)  If
10: // the "inverse" method threw a checked exception than it would need to be
11: // declared with a "throws" clause, something similar to this:
12: //      float inverse ( float num ) throws WhatEverException
13: //
14: // You can find a list of standard Exceptions in java.lang (and other)
15: // packages, in the JavaDocs.
16: //
17: // Written 3/2006 by Wayne Pollock, Tampa Florida USA.
18: 
19: import javax.swing.JOptionPane;
20: 
21: class ExceptionDemo
22: {
23:    public static void main ( String [] args )
24:    {
25:       int num = 0;
26:       String input = JOptionPane.showInputDialog( "Enter a number:" );
27:       try
28:       {
29:          num = Integer.parseInt( input );
30:          System.out.println( "The inverse of " + num + " is " + inverse(num) );
31:       }
32:       catch ( NumberFormatException e )
33:       {
34:          System.out.println( "\"" + input + "\" is not a number!" );
35:       }
36:       // Comment out the following catch clause, run with "0" (zero), and
37:       // see the default error handler output.
38:       catch ( IllegalArgumentException e )
39:       {
40:          System.out.println( e.getMessage() );
41:       }
42:    }
43: 
44:    static float inverse ( float num )  // throws IllegalArgumentException
45:    {
46:       if ( num == 0.0f )
47:          throw new IllegalArgumentException( "num must not be zero!" );
48: 
49:       return 1 / num;
50:    }
51: }