An Introduction to Exceptions - Ch. 1

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    An Introduction to Exceptions - Ch. 1

    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:
    [CODE=java]
    public double div(double a, double b)
    {
    return a/b;
    }
    [/CODE]You try:
    [CODE=java]
    System.out.prin tln("2.0 / 3.0 = " + div(2.0,3.0));
    // 2.0 / 3.0 = 0.6666666666666 666
    System.out.prin tln("6.0 / 2.0 = " + div(6.0,2.0));
    // 6.0 / 2.0 = 3.0
    System.out.prin tln("1.0 / 0.0 = " + div(1.0,0.0));
    // 1.0 / 0.0 = Infinity
    [/CODE]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
    [CODE=java]
    double d;
    if(div(1.,0.) == Infinity) d = 1;
    else d = div(1.,0.);
    System.out.prin tln("1.0 / 0.0 = " + c);
    [/CODE]or this
    [CODE=java]
    double c = (div(1.,0.) == Infinity) ? 1. : div(1.,0.);
    System.out.prin tln("1.0 / 0.0 = " + c);
    [/CODE]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:
    [CODE=java]
    public double div(double a, double b) throws Exception
    {
    if (b==0) throw new Exception();
    return a/b;
    }
    [/CODE]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:
      [CODE=java]
      if (b==0) throw new Exception();
      [/CODE]
      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
    Last edited by RedSon; Dec 18 '07, 06:28 PM. Reason: Editing
Working...