Saturday, April 3, 2010

A window into Exceptions

A friend of mine asked me what exceptions are, and here is my reply in the English language of humans, as opposed to computer jargon.
I will discuss the concept of Exceptions in computer programming. Depending in the programming language you will use, it might come in a different keyword but the concept stands.

An Exception is an unexpected situation/state. When writing a computer program, you have to anticipate all possible states that the program might take during execution. For each possible state that the program would take, you have to tell it what to do. If a program takes a state which was not anticipated by the programmer, it doesn't know what to do and therefore it crashes, popularly referred as throwing an exception in some languages. For example, Lets take a program for dividing two numbers. The basic flow would be: request the user to enter the first number, then the second number, divide them and print the result on the screen. This program as described would be consist of sequential instructions, it assumes all inputs will be 'dividable' which is very wrong. In most circumstances it would run right, but there are two circumstances in which it wont:-
1. If the user entered a non-numerical input, the program would 'throw a fatal exception', in that it would crash with an error.
2. If the user entered a zero denominator, its not possible to divide a number by zero and this would result to a fatal exception too.

So whats the solutions. There are two ways of doing the program right:-

1. Validating input - after each input, the computer validates if the input is numerical, if its not, it doesn't perform the division but instead it prints an error message e.g "Error, invalid input". By doing this, the program does not crash on non-numerical input.
Once the program validates the inputs, it compares the second input (denominator) with zero, if they are equal, it reframes from the division and prints an error message.
If the denominator is not zero, the program may now perform the division and print the result.

2. Handling Exceptions - This means enclosing the program instructions which might throw exceptions in a 'Try...Catch' block. If anything fatal happens in the 'try' block, the program jumps into 'catch' block without crashing. Its therefore common to print an error message in the catch block, the message will be printed only if the program encounters an error. Not all programming languages support this, but most modern languages support it, it comes in differing keywords depending on the programming language.

For those who have a thing for programming, here is sample code in Java and python that demonstrates handling Exceptions, the second approach.

//In Java
import java.util.Scanner;
public class Example{
public static void main(String[] args ){
Scanner read=new Scanner(System.in);
int num1=0,num2=0, result=0;
System.out.println("This program divides two numbers and prints the result");
try{
System.out.println("Enter the numerator");
num1=read.nextInt();
System.out.println("Enter the denominator");
num2=read.nextInt();
}catch(Exception e){
System.out.println("You entered invalid numbers");
System.exit(0);
}
try{
result=num1/num2;
System.out.println("The result is "+result);
}catch(Exception e){
System.out.println("You cannot divide by zero");
}
}
}


#In Python
num1=0
num2=0
result=0
print"This program divides two numbers and prints the result"
try:
print "Enter the numerator"
num1=int(raw_input())
print "Enter the denominator"
num2=int(raw_input())
except:
print "You entered invalid numbers"
exit(0)
try:
result=num1/num2;
print "The result is ",result
except:
print "You cannot divide by zero"

There are different types of Exceptions and its possible to specify to the program on how to handle each type of Exception. For example, the Non-numerical input error would throw a 'NumberFormatException' in Java and a 'ValueError' in Python. A better version of the above program would specifically anticipate such exceptions.

2 comments:

  1. And there is no stopping. Just putting my writing skills to test and having fun.

    ReplyDelete