Connecting Tech Pros Worldwide Forums | Help | Site Map

An Introduction to Exceptions - Ch. 5

Nepomuk's Avatar
Moderator
 
Join Date: Aug 2007
Location: Germany
Posts: 2,466
#1   Sep 19 '07
Chapter 5: An Example of how to use Exceptions
As Exceptions might be new to you, here is an example of a very basic Text Adventure, that uses Exceptions. It is merely to give you an idea of how to use them in a real context - but of course, you're welcome to use it (you can hardly say "play it") and, if you want to, extend it.
Expand|Select|Wrap|Line Numbers
  1. import java.io.IOException;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Chapter5 {
  6.     private static Scanner scanner = new Scanner(System.in);
  7.     /**
  8.      * It should be known, if the light is on or off.
  9.      */
  10.     private static boolean lightIsOn = true;
  11.     private static boolean roomHasLightSwitch = true;
  12.     private static boolean canTalk = true;
  13.  
  14.     public static void main(String[] args)
  15.     {
  16.         while(true)
  17.         {
  18.             try
  19.             {
  20.                 checkCommand();
  21.             }
  22.             catch(ActionNotPossibleException anpe)
  23.             {
  24.                 System.err.println(anpe);
  25.                 if(!anpe.getCause().toString().equals(null))
  26.                     System.err.println("\t" + anpe.getCause());
  27.             }
  28.         }
  29.     }
  30.  
  31.     /**
  32.      * Checks, what command the user has given.
  33.      * @throws ActionNotPossibleException
  34.      */
  35.     private static void checkCommand() throws ActionNotPossibleException
  36.     {
  37.         String command = scanner.nextLine(); 
  38.  
  39.         if(command.toLowerCase().startsWith("look at"))
  40.         {
  41.             lookAt(command.substring(8));
  42.         }
  43.         else if(command.toLowerCase().startsWith("move switch"))
  44.         {
  45.             moveSwitch();
  46.         }
  47.         else if(command.toLowerCase().startsWith("say"))
  48.         {
  49.             saySomething(command.substring(4));
  50.         }
  51.         else if(command.toLowerCase().startsWith("shout at"))
  52.         {
  53.             shoutAt(command.substring(9));
  54.         }
  55.         else if(command.toLowerCase().startsWith("quit"))
  56.             System.exit(1);
  57.         else System.out.println("Don't know that command.");
  58.     }
  59.  
  60.     /**
  61.      * Switch the light on if it's off and off if it's on.
  62.      */
  63.     public static void moveSwitch() throws ActionNotPossibleException
  64.     {
  65.         lightIsOn = !lightIsOn;
  66.         if(roomHasLightSwitch)
  67.         {
  68.             if(lightIsOn) System.out.println("You switched the light on.");
  69.             else System.out.println("You switched the light off.");
  70.         }
  71.         else throw new ActionNotPossibleException("move the light switch","You can't find a light switch.");
  72.     }
  73.  
  74.     /**
  75.      * Look at the targeted Object and give a comment about it.
  76.      * @param target
  77.      * @throws ActionNotPossibleNowException
  78.      */
  79.     public static void lookAt(String target) throws ActionNotPossibleException
  80.     {
  81.         if(!lightIsOn) throw new ActionNotPossibleException("look at " + target, "It is dark.");
  82.         else
  83.         {
  84.             System.out.println("You look at the " + target + ". It's boring.\n");
  85.         }
  86.     }
  87.  
  88.     /**
  89.      * Say something.
  90.      * @param sentence
  91.      * @throws UnableToSpeakException
  92.      */
  93.     public static void saySomething(String sentence) throws UnableToSpeakException
  94.     {
  95.         if(canTalk)
  96.         {
  97.             System.out.println(sentence + "\n");
  98.         }
  99.         else throw new UnableToSpeakException("Maybe you should shut up sometimes.");
  100.     }
  101.  
  102.     /**
  103.      * Shout at someone or something. It is of course one way of saying
  104.      * something (even though a very unfriendly way).
  105.      * @param target
  106.      * @throws UnableToSpeakException
  107.      */
  108.     public static void shoutAt(String target) throws UnableToSpeakException
  109.     {
  110.         try
  111.         {
  112.             lookAt(target);
  113.             System.out.println("You shout: \"SLARTIBARTFAST\" at " + target + ". No reaction.");
  114.         }
  115.         catch(ActionNotPossibleException anpe)
  116.         {
  117.             UnableToSpeakException utse = new UnableToSpeakException("");
  118.             utse.initCause(anpe);
  119.             throw utse;
  120.         }
  121.     }
  122. }
  123.  
And the two Exceptions, we use:
Expand|Select|Wrap|Line Numbers
  1. /**
  2.  * Our selfdefined Exception "ActionNotPossibleNowException".
  3.  */
  4. class ActionNotPossibleException extends IOException
  5. {
  6.     // This is just to make sure, the compiler compiles without giving a warning.
  7.     // However, if you should continue developing this game, you might want to change
  8.     // the Version UID.
  9.     private static final long serialVersionUID = 1L;
  10.     public ActionNotPossibleException(String action, String reason)
  11.     {
  12.         super("Could not " + action + " now. Reason: " + reason);
  13.     }
  14. }
  15.  
  16. /**
  17.  * A second selfdefined Exception "UnableToSpeakException", which is an "ActionNotPossibleException".
  18.  */
  19. class UnableToSpeakException extends ActionNotPossibleException
  20. {
  21.     private static final long serialVersionUID = 1L;
  22.     public UnableToSpeakException(String reason)
  23.     {
  24.         super("speak",reason);
  25.     }
  26. }
  27.  
I hope, you now understand a little more about what Exceptions are and how to use them in a productive way.

Back to chapter 4
Attached Files
File Type: zip Chapter5.zip (1.3 KB, 73 views)



Reply