Chapter 4: How can I write my own exceptions?
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:
-
public class ActionNotPossibleNowException extends Exception {
-
public ActionNotPossibleNowException(String action, String reason)
-
{
-
super("Could not " + action + " now. Reason: " + reason);
-
}
-
}
-
As you see, it's not any different to any other Superclass relationship. All we have to know, is that
Exception has a constructor, which takes a String as an argument and this String is the error message.
So, now you can have a method
lookAt in your character class, which would look something like this:
-
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
-
{
-
...
-
}
-
}
-
}
-
Of course, you can extend any other given Exception as well - if you decide, that the
ActionNotPossibleNowException is actually an Input-Output-Exception (IOException), simply change the code to
-
public class ActionNotPossibleNowException extends IOException {
-
public ActionNotPossibleNowException(String action, String reason)
-
{
-
super("Could not " + action + " now. Reason: " + reason);
-
}
-
}
-
Which can now be caught any of these lines:
-
catch(ActionNotPossibleNowException anpne){...}
-
catch(IOException ioe){...}
-
catch(Exception e){...}
-
Often, you should not extend Exception directly, but a more specialized Exception. For example
- class NoKeyPressedException extends IOException {
-
// ...
-
}
-
and
- class NoMouseButtonPressedException extends IOException {
-
// ...
-
}
-
will both be caught by
- catch(IOException ioe) {
-
//...
-
}
-
and you can still have a third exception
-
class ThirdException extends Exception {
-
//...
-
}
-
which isn't caught by that catch-block and can be handled separately. You can solve this differently, however this is a easy and sufficient way of doing so.
Back to chapter 3 or
Continue to chapter 5