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.
And the two Exceptions, we use:
-
/**
-
* Our selfdefined Exception "ActionNotPossibleNowException".
-
*/
-
class ActionNotPossibleException 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 serialVersionUID = 1L;
-
public ActionNotPossibleException(String action, String reason)
-
{
-
super("Could not " + action + " now. Reason: " + reason);
-
}
-
}
-
-
/**
-
* A second selfdefined Exception "UnableToSpeakException", which is an "ActionNotPossibleException".
-
*/
-
class UnableToSpeakException extends ActionNotPossibleException
-
{
-
private static final long serialVersionUID = 1L;
-
public UnableToSpeakException(String reason)
-
{
-
super("speak",reason);
-
}
-
}
-
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