Now we have seen, how you can work with the Exceptions, which are supplied and what some of the most common of them mean. However, just imagine you want to throw an Exception, which doesn't fit with any Exception there is predefined?
Example:
You have written your own text adventure (yes, they are old fashioned, but they still exist) and you want to throw an Exception, when a command is valid, but can't be used in this situation (e.g. "look at door" when it's dark).
You can use if-statements here, but let's just choose to use Exceptions in this case.
What you want now is a ActionNotPossibleNowException. You want to tell it, what can't be done and why it can't be done and it should give you an output, which covers both.
This can be coded like this:
Expand|Select|Wrap|Line Numbers
- public class ActionNotPossibleNowException extends Exception {
- public ActionNotPossibleNowException(String action, String reason)
- {
- super("Could not " + action + " now. Reason: " + reason);
- }
- }
So, now you can have a method lookAt in your character class, which would look something like this:
Expand|Select|Wrap|Line Numbers
- public class Character {
- private boolean lightIsOn = true;
- ...
- public void lookAt(String target) throws ActionNotPossibleNowException
- {
- if(!lightIsOn) throw new ActionNotPossibleNowException("look at " + target, "It is dark.");
- else
- {
- ...
- }
- }
- }
Expand|Select|Wrap|Line Numbers
- public class ActionNotPossibleNowException extends IOException {
- public ActionNotPossibleNowException(String action, String reason)
- {
- super("Could not " + action + " now. Reason: " + reason);
- }
- }
Expand|Select|Wrap|Line Numbers
- catch(ActionNotPossibleNowException anpne){...}
- catch(IOException ioe){...}
- catch(Exception e){...}
Expand|Select|Wrap|Line Numbers
- class NoKeyPressedException extends IOException {
- // ...
- }
Expand|Select|Wrap|Line Numbers
- class NoMouseButtonPressedException extends IOException {
- // ...
- }
Expand|Select|Wrap|Line Numbers
- catch(IOException ioe) {
- //...
- }
Expand|Select|Wrap|Line Numbers
- class ThirdException extends Exception {
- //...
- }
Back to chapter 3 or Continue to chapter 5