|
RumpelStiltskinDemo |
|
1 // Example 7.1 joi/examples/RumpelStiltskinDemo.java
2 //
3 //
4 // Copyright 2003 Bill Campbell and Ethan Bolker
5
6 // Practice with simple exceptions - some from the API, one declared here.
7
8 public class RumpelStiltskinDemo
9 {
10 public static void main( String[] args )
11 {
12 Wizard rumpelstiltskin = new Wizard("RumpelStiltskin");
13 Wizard aNullWizard = null;
14
15 // see if the first command line argument ( args[0] )
16 // is the right name
17 try {
18 System.out.println("Is your name " + args[0] +'?');
19 rumpelstiltskin.guessName(args[0]);
20 System.out.println("Yes! How did you guess?");
21 System.exit(0);
22 }
23 // come here right away if there is no args[0]
24 catch (IndexOutOfBoundsException e) {
25 System.out.println( "usage: java RumpelStiltskinDemo guess");
26 System.exit(0); // leave the program gracefully
27 }
28 // come here from guessName if exception thrown
29 catch (BadGuessException e) {
30 System.err.println("sorry - " + args[0] + " is not my name");
31 }
32
33 System.out.println(
34 "\nIntentionally generate a NullPointerException,\n" +
35 "see what the Exception's toString method returns");
36 try {
37 aNullWizard.guessName("who am I?");
38 }
39 catch (Exception e) {
40 System.out.println(e);
41 }
42
43 System.out.println(
44 "\nExperiment with the printStackTrace() method:");
45 try {
46 rumpelstiltskin.makeMischief();
47 }
48 catch (Exception e) {
49 e.printStackTrace();
50 }
51
52 // perhaps throw an uncaught IndexOutOfBoundsException
53 System.out.println(
54 "\nLook for a second command line argument,\n" +
55 "see what happens if it's not there:" );
56 System.out.println(args[1]);
57 }
58
59 // two inner classes, used only in this file
60 private static class Wizard
61 {
62 private String name;
63
64 public Wizard( String name )
65 {
66 this.name = name;
67 }
68
69 public void guessName( String name )
70 throws BadGuessException
71 {
72 if (!name.equals(this.name))
73 throw new BadGuessException( );
74 }
75
76 public void makeMischief()
77 throws BadGuessException
78 {
79 this.guessName("??");
80 }
81 }
82
83 private static class BadGuessException extends Exception
84 {
85 // empty body
86 }
87 }
88
|
RumpelStiltskinDemo |
|