473,419 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,419 developers and data experts.

An Introduction to Exceptions - Ch. 5

Nepomuk
3,112 Expert 2GB
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, 189 views)
Sep 19 '07 #1
0 3569

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Cletis Tout | last post by:
http://www.codeproject.com/cpnet/introtomono1.asp Introduction to Mono - Your first Mono app By Brian Delahunty The first in a series of articles about Mono. This article explains how to...
14
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of...
12
by: Xah Lee | last post by:
Of Interest: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html Currently, this introduction introduces you to the graphics format of Mathematica, and two Java Applet...
2
by: Jeroen | last post by:
We are experiencing a tuff-to-debug problem ever since we introduced a WebBrowser control into our failry large application. I'm not sure if the problem description below contains enough details,...
5
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is...
0
by: r035198x | last post by:
Inheritance We have already covered one important concept of object-oriented programming, namely encapsulation, in the previous article. These articles are not articles on object oriented...
0
RedSon
by: RedSon | last post by:
Chapter 2: How to handle Exceptions When you call a program, sometimes you get a message about an Unhandled exception type. This means, that something throws (or might throw) an Exception, but the...
0
Nepomuk
by: Nepomuk | last post by:
Chapter 1: What is an Exception? Imagine, you want to write a program for calculating. You start, it works fine, you can add, subtract, multiply and divide. Then there's a question: What about the...
0
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.