Pages

Friday, February 4, 2011

Exception Handling in Python...

Python:
Exception Handling is a bit difficult in Python, If you are from Java Background.
Because In Java, We will use

try{
}
catch(Exception E){
System.out.println ( E.getMessage () );
E.printStackTrace();
}

Where E is a generic Exception...
That is, this will  handle all types of Exceptions.
In Java, java.lang.Exception is the super class for all Exceptions.
So this helps the lazy programmers (!) to handle exceptions..


But in Python, its a bit different..

try:
    1/0
except:
    print "Sorry:", sys.exc_type, ":", sys.exc_value

( And )

You can handle Array Index Out of Bounds Exception like this..

try:


except IndexError:
   print "Array Index Out of Bounds Exception"

(And)

You can handle IOException like this.

try:

except IOError:
  print "IO Error"

(And)

You can handle NumberFormatException like this.

try:
         x = int(raw_input("Please enter a number: "))
 
except ValueError:
        print "Oops!  That was no valid number.  Try again..."

( And )

You can handle DivideByZeroException like this.
 
try:
        result = x / y
except ZeroDivisionError:
        print "division by zero!"

For More details about exceptions in Python, please refer this link..

http://www.python.org/doc/essays/stdexceptions.html

No comments:

Post a Comment