Sunday 3 July 2011

Exception and Exception handling in python

    Exceptions are general programming technique for altering the regular program flow in special cases such as errors or incorrect input.
     Like many other programming languages, python has exception handling via try...except blocks. Python uses try ... except to handle exceptions and raise to generate them. Java and C++ use try ...catch to handle exceptions, and throw to generate them. 
Exceptions
Exceptions are errors, that are detected during the execution of code. In this post I want to explain how we can handle this types of exceptions. Most exceptions are not handled by programs. In such situations we can generate an error message.
Various types of exceptions are ZeroDivisionError,NameError and TypeError.
Example for ZeroDivisionError
>>> 20*(2/0)
Output
ZeroDivisionError: integer division or modulo by zero
Here we try to divide 2 by zero, this is an example for ZeroDivisionError.

Example for NameError
>>> 5+spam*3
Output
NameError: name 'spam' is not defined
Example for TyeError
>>> '6'+3
Output
TypeError: cannot concatenate 'str' and 'int' objects
Exception Handling
    We can catch or handle an exception which a piece of code may generate by putting that piece of code inside of a try block and then specifying corresponding except block.
Example
>>> try:
... some_func()
... except:
... print 'Caught an exception in "some_func()".Exiting.'
... exit(1)
...
Caught an exception in "some_func()".Exiting.
In this example function 'some_func()' generate an error, here we write this function in try block, corresponding solutions are write in the except block.
Multiple except blocks may be associated with a given try block. The first except which matches the type of exception raised will be executed.
Example
>>> try:
... some_func()
... except FoolException,e:
... print 'Caught a FoolException. Exiting.'
... exit(1)
... except RuntimeError,e:
... print 'Caught a RuntimeError. Exiting.'
... exit(10)
... except:
... print 'caught an exception in "some_func()". Exiting'
... exit(100)
Raising Exceptions
The raise statement allows the programmer to force a specified exception to occur.
Example
>>> foo=56
>>> if foo==56: raise RuntimeError("Can't continue - foo is 56")
Output
RuntimeError: Can't continue - foo is 56
finally
There may be some code (like closing a file) that you need to execute no matter whether the code before that raises an exception or runs smoothly. We can put such code in finally block.
Example
>>> fname='file-name.txt'
>>> try:
... f=file(fname)
... except IOError:
... print "File %s could not be opened for reading. Closing."% fname
... exit(1)

>>> try:
... process_file(f)
... finally:
... f.close()
In this example first uses a try block to safely open a file for reading and then uses a try and finally to ensure that the file gets closed.

No comments:

Post a Comment