473,326 Members | 2,010 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,326 developers and data experts.

An Introduction to Exceptions - Ch. 4

Nepomuk
3,112 Expert 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. public class ActionNotPossibleNowException extends Exception {
  2.     public ActionNotPossibleNowException(String action, String reason)
  3.     {
  4.         super("Could not " + action + " now. Reason: " + reason);
  5.     }
  6. }
  7.  
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:
Expand|Select|Wrap|Line Numbers
  1. public class Character {
  2.     private boolean lightIsOn = true;
  3.  
  4.     ...
  5.  
  6.     public void lookAt(String target) throws ActionNotPossibleNowException
  7.     {
  8.         if(!lightIsOn) throw new ActionNotPossibleNowException("look at " + target, "It is dark.");
  9.         else
  10.         {
  11.             ...
  12.         }
  13.     }
  14. }
  15.  
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
Expand|Select|Wrap|Line Numbers
  1. public class ActionNotPossibleNowException extends IOException {
  2.     public ActionNotPossibleNowException(String action, String reason)
  3.     {
  4.         super("Could not " + action + " now. Reason: " + reason);
  5.     }
  6. }
  7.  
Which can now be caught any of these lines:
Expand|Select|Wrap|Line Numbers
  1. catch(ActionNotPossibleNowException anpne){...}
  2. catch(IOException ioe){...}
  3. catch(Exception e){...}
  4.  
Often, you should not extend Exception directly, but a more specialized Exception. For example
Expand|Select|Wrap|Line Numbers
  1. class NoKeyPressedException extends IOException {
  2.    // ... 
  3. }
  4.  
and
Expand|Select|Wrap|Line Numbers
  1. class NoMouseButtonPressedException extends IOException {
  2.    // ... 
  3. }
  4.  
will both be caught by
Expand|Select|Wrap|Line Numbers
  1. catch(IOException ioe) {
  2.    //...
  3. }
  4.  
and you can still have a third exception
Expand|Select|Wrap|Line Numbers
  1. class ThirdException extends Exception {
  2.    //...
  3. }
  4.  
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
Attached Files
File Type: zip Chapter4.zip (715 Bytes, 187 views)
Sep 19 '07 #1
0 3617

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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.