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
- public double div(double a, double b)
- {
- return a/b;
- }
Expand|Select|Wrap|Line Numbers
- System.out.println("2.0 / 3.0 = " + div(2.0,3.0));
- // 2.0 / 3.0 = 0.6666666666666666
- System.out.println("6.0 / 2.0 = " + div(6.0,2.0));
- // 6.0 / 2.0 = 3.0
- System.out.println("1.0 / 0.0 = " + div(1.0,0.0));
- // 1.0 / 0.0 = Infinity
However, just doing something like this
Expand|Select|Wrap|Line Numbers
- double d;
- if(div(1.,0.) == Infinity) d = 1;
- else d = div(1.,0.);
- System.out.println("1.0 / 0.0 = " + c);
Expand|Select|Wrap|Line Numbers
- double c = (div(1.,0.) == Infinity) ? 1. : div(1.,0.);
- System.out.println("1.0 / 0.0 = " + c);
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
- public double div(double a, double b) throws Exception
- {
- if (b==0) throw new Exception();
- return a/b;
- }
- We have added "throws Exception" to the methods head. This just tells the compiler, that this method might throw an Exception.
- We have added a new line to the program:
Expand|Select|Wrap|Line Numbers- if (b==0) throw new Exception();
Continue to chapter 2