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.
[CODE=java]
import java.io.IOExcep tion;
import java.util.Scann er;
public class Chapter5 {
private static Scanner scanner = new Scanner(System. in);
/**
* It should be known, if the light is on or off.
*/
private static boolean lightIsOn = true;
private static boolean roomHasLightSwi tch = true;
private static boolean canTalk = true;
public static void main(String[] args)
{
while(true)
{
try
{
checkCommand();
}
catch(ActionNot PossibleExcepti on anpe)
{
System.err.prin tln(anpe);
if(!anpe.getCau se().toString() .equals(null))
System.err.prin tln("\t" + anpe.getCause() );
}
}
}
/**
* Checks, what command the user has given.
* @throws ActionNotPossib leException
*/
private static void checkCommand() throws ActionNotPossib leException
{
String command = scanner.nextLin e();
if(command.toLo werCase().start sWith("look at"))
{
lookAt(command. substring(8));
}
else if(command.toLo werCase().start sWith("move switch"))
{
moveSwitch();
}
else if(command.toLo werCase().start sWith("say"))
{
saySomething(co mmand.substring (4));
}
else if(command.toLo werCase().start sWith("shout at"))
{
shoutAt(command .substring(9));
}
else if(command.toLo werCase().start sWith("quit"))
System.exit(1);
else System.out.prin tln("Don't know that command.");
}
/**
* Switch the light on if it's off and off if it's on.
*/
public static void moveSwitch() throws ActionNotPossib leException
{
lightIsOn = !lightIsOn;
if(roomHasLight Switch)
{
if(lightIsOn) System.out.prin tln("You switched the light on.");
else System.out.prin tln("You switched the light off.");
}
else throw new ActionNotPossib leException("mo ve the light switch","You can't find a light switch.");
}
/**
* Look at the targeted Object and give a comment about it.
* @param target
* @throws ActionNotPossib leNowException
*/
public static void lookAt(String target) throws ActionNotPossib leException
{
if(!lightIsOn) throw new ActionNotPossib leException("lo ok at " + target, "It is dark.");
else
{
System.out.prin tln("You look at the " + target + ". It's boring.\n");
}
}
/**
* Say something.
* @param sentence
* @throws UnableToSpeakEx ception
*/
public static void saySomething(St ring sentence) throws UnableToSpeakEx ception
{
if(canTalk)
{
System.out.prin tln(sentence + "\n");
}
else throw new UnableToSpeakEx ception("Maybe you should shut up sometimes.");
}
/**
* Shout at someone or something. It is of course one way of saying
* something (even though a very unfriendly way).
* @param target
* @throws UnableToSpeakEx ception
*/
public static void shoutAt(String target) throws UnableToSpeakEx ception
{
try
{
lookAt(target);
System.out.prin tln("You shout: \"SLARTIBARTFAS T\" at " + target + ". No reaction.");
}
catch(ActionNot PossibleExcepti on anpe)
{
UnableToSpeakEx ception utse = new UnableToSpeakEx ception("");
utse.initCause( anpe);
throw utse;
}
}
}
[/CODE]And the two Exceptions, we use:
[CODE=java]
/**
* Our selfdefined Exception "ActionNotPossi bleNowException ".
*/
class ActionNotPossib leException extends IOException
{
// This is just to make sure, the compiler compiles without giving a warning.
// However, if you should continue developing this game, you might want to change
// the Version UID.
private static final long serialVersionUI D = 1L;
public ActionNotPossib leException(Str ing action, String reason)
{
super("Could not " + action + " now. Reason: " + reason);
}
}
/**
* A second selfdefined Exception "UnableToSpeakE xception", which is an "ActionNotPossi bleException".
*/
class UnableToSpeakEx ception extends ActionNotPossib leException
{
private static final long serialVersionUI D = 1L;
public UnableToSpeakEx ception(String reason)
{
super("speak",r eason);
}
}
[/CODE]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
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.
[CODE=java]
import java.io.IOExcep tion;
import java.util.Scann er;
public class Chapter5 {
private static Scanner scanner = new Scanner(System. in);
/**
* It should be known, if the light is on or off.
*/
private static boolean lightIsOn = true;
private static boolean roomHasLightSwi tch = true;
private static boolean canTalk = true;
public static void main(String[] args)
{
while(true)
{
try
{
checkCommand();
}
catch(ActionNot PossibleExcepti on anpe)
{
System.err.prin tln(anpe);
if(!anpe.getCau se().toString() .equals(null))
System.err.prin tln("\t" + anpe.getCause() );
}
}
}
/**
* Checks, what command the user has given.
* @throws ActionNotPossib leException
*/
private static void checkCommand() throws ActionNotPossib leException
{
String command = scanner.nextLin e();
if(command.toLo werCase().start sWith("look at"))
{
lookAt(command. substring(8));
}
else if(command.toLo werCase().start sWith("move switch"))
{
moveSwitch();
}
else if(command.toLo werCase().start sWith("say"))
{
saySomething(co mmand.substring (4));
}
else if(command.toLo werCase().start sWith("shout at"))
{
shoutAt(command .substring(9));
}
else if(command.toLo werCase().start sWith("quit"))
System.exit(1);
else System.out.prin tln("Don't know that command.");
}
/**
* Switch the light on if it's off and off if it's on.
*/
public static void moveSwitch() throws ActionNotPossib leException
{
lightIsOn = !lightIsOn;
if(roomHasLight Switch)
{
if(lightIsOn) System.out.prin tln("You switched the light on.");
else System.out.prin tln("You switched the light off.");
}
else throw new ActionNotPossib leException("mo ve the light switch","You can't find a light switch.");
}
/**
* Look at the targeted Object and give a comment about it.
* @param target
* @throws ActionNotPossib leNowException
*/
public static void lookAt(String target) throws ActionNotPossib leException
{
if(!lightIsOn) throw new ActionNotPossib leException("lo ok at " + target, "It is dark.");
else
{
System.out.prin tln("You look at the " + target + ". It's boring.\n");
}
}
/**
* Say something.
* @param sentence
* @throws UnableToSpeakEx ception
*/
public static void saySomething(St ring sentence) throws UnableToSpeakEx ception
{
if(canTalk)
{
System.out.prin tln(sentence + "\n");
}
else throw new UnableToSpeakEx ception("Maybe you should shut up sometimes.");
}
/**
* Shout at someone or something. It is of course one way of saying
* something (even though a very unfriendly way).
* @param target
* @throws UnableToSpeakEx ception
*/
public static void shoutAt(String target) throws UnableToSpeakEx ception
{
try
{
lookAt(target);
System.out.prin tln("You shout: \"SLARTIBARTFAS T\" at " + target + ". No reaction.");
}
catch(ActionNot PossibleExcepti on anpe)
{
UnableToSpeakEx ception utse = new UnableToSpeakEx ception("");
utse.initCause( anpe);
throw utse;
}
}
}
[/CODE]And the two Exceptions, we use:
[CODE=java]
/**
* Our selfdefined Exception "ActionNotPossi bleNowException ".
*/
class ActionNotPossib leException extends IOException
{
// This is just to make sure, the compiler compiles without giving a warning.
// However, if you should continue developing this game, you might want to change
// the Version UID.
private static final long serialVersionUI D = 1L;
public ActionNotPossib leException(Str ing action, String reason)
{
super("Could not " + action + " now. Reason: " + reason);
}
}
/**
* A second selfdefined Exception "UnableToSpeakE xception", which is an "ActionNotPossi bleException".
*/
class UnableToSpeakEx ception extends ActionNotPossib leException
{
private static final long serialVersionUI D = 1L;
public UnableToSpeakEx ception(String reason)
{
super("speak",r eason);
}
}
[/CODE]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