469,635 Members | 2,395 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Share your developer knowledge by writing an article on Bytes.

An Introduction to Exceptions - Ch. 1

Nepomuk
3,112 Expert 2GB
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 division by zero?
Say, your division method looks like this:
Expand|Select|Wrap|Line Numbers
  1. public double div(double a, double b)
  2.     {
  3.         return a/b;
  4.     }
  5.  
You try:
Expand|Select|Wrap|Line Numbers
  1. System.out.println("2.0 / 3.0 = " + div(2.0,3.0));
  2. // 2.0 / 3.0 = 0.6666666666666666
  3. System.out.println("6.0 / 2.0 = " + div(6.0,2.0));
  4. // 6.0 / 2.0 = 3.0
  5. System.out.println("1.0 / 0.0 = " + div(1.0,0.0));
  6. // 1.0 / 0.0 = Infinity
  7.  
The answer you get is "Infinity". This answer isn't very pleasing, you want it to give an error.
However, just doing something like this
Expand|Select|Wrap|Line Numbers
  1. double d;
  2. if(div(1.,0.) == Infinity) d = 1;
  3. else d = div(1.,0.);
  4. System.out.println("1.0 / 0.0 = " + c);
  5.  
or this
Expand|Select|Wrap|Line Numbers
  1. double c = (div(1.,0.) == Infinity) ? 1. : div(1.,0.);
  2. System.out.println("1.0 / 0.0 = " + c);
  3.  
won't work - the compiler will tell you that Infinity cannot be resolved. So, what do you do?

In many programming languages, such as Java, the creators of the language thought about this sort of problem and found a solution: Exceptions.
A function, which should give back a value can always throw an exception instead. The function is then terminated, without having fulfilled it's actual task.

In this case, it would look something like this:
Expand|Select|Wrap|Line Numbers
  1. public double div(double a, double b) throws Exception
  2.     {
  3.         if (b==0) throw new Exception();
  4.         return a/b;
  5.     }
  6.  
Now, what have we done?
  1. We have added "throws Exception" to the methods head. This just tells the compiler, that this method might throw an Exception.
  2. We have added a new line to the program:
    Expand|Select|Wrap|Line Numbers
    1. if (b==0) throw new Exception();
    2.  
    This checks, if b is zero and if so it throws a new Exception. Then the function stops and doesn't return any value.
If you compile your program now, it will tell you that there is an Unhandled exception type Exception. This will be covered in the next chapter.

Continue to chapter 2
Attached Files
File Type: zip Chapter1.zip (823 Bytes, 177 views)
Sep 19 '07 #1
0 3468

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

14 posts views Thread by Cletis Tout | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.