Exception handling in python - try/except/else/finally

Exceptions are unexpected events that occur during the execution of a program.Consider the following where exception/error occurs:
>>> 10 * (1/0)     #ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3  #NameError: name 'spam' is not declared 
>>> '2' + 2     #TypeError: cannot concatenate 'str' and 'int' objects
Here ZeroDivisionError, NameError and TypeError are name of the built-in exception that occurred.Standard exception names are built-in identifiers (not reserved keywords).
1. In Python, exceptions (also known as errors) are objects that are raised (or thrown) by
code that encounters an unexpected circumstance.
2. A raised error may be caught by a surrounding context that “handles” the exception in an appropriate fashion.
3. If Exception occurs and If uncaught, an exception causes the interpreter
to stop executing the program.
Following are list of common exception class found in python:(Image from DSA by Goodrich
Common exception classes in Python

Exception handling/catching in python is carried out using  try .. except statements. Let's take an example to understand try and except statements. Below mentioned code snippet expect user to enter some valid input, however user press "Ctrl+ d" or "Ctrl+c"(KeyboardInterrupt).
try:
    text = raw_input('Enter a valid input --> ')
except EOFError: # Press ctrl + d
    print 'End of file is pressed.'
except KeyboardInterrupt: # Press ctrl + c
    print 'Operation cancelled ..'
else: #if No exception occurred, optional else block is executed 
    print 'You entered {}'.format(text)
Sample output:
>>>
Enter valid input --> # ctrl+c is pressed
Operation cancelled .
>>>
Enter valid input --> test_input
You entered test_input

Notes:- 
1. Normal operational code lines are placed inside try block, as in above example valid user input is
    expected in try block. i.e : Watch for exception in try block.
2. Once exception occurs corresponding except block gets executed.
3. with one try block there can be N number of except block and there has to be at least one except
    clause associated with every try
clause.
4. We can also have an optional else clause associated with a try..except block. The else clause is executed if no exception occurs.
5. If an exception is not caught within the body of the function, the execution of the function
    immediately ceases and the exception is propagated to the calling context.

Exception raising in python is carried out using raise statement with an appropriate instance
of an exception class as an argument. i.e: The error or exception that you can raise should be a class which directly or indirectly must be a derived class of the Exception class. Consider an example to understand how we can raise an exception. Find square root of an number and raise an exception when user input is negative(Square root of a negative number is imaginary value).
Open Python IDLE. Create a new file and copy following codes.
import math
def sqrtC(x):
    if not isinstance(x, (int, float)):
        raise TypeError( "x must be numeric" )
    elif x < 0:
        raise ValueError( "x cannot be negative" )
    else: 
        print 'Square root of number is %f' %math.sqrt( x )

#sqrt(input)
input = int(raw_input("Enter number: "))
try:
    sqrtC(input)
except TypeError:
    print 'TypeError type caught, x is not numeric!!'
except ValueError:
    print 'ValueError type caught, Input is negative!!'
Sample output:
>>>
Enter number: 25
Sqaure root of number is 5.000000
>>>
Enter number: -25
ValueError type caught, Input is negative!!

Lets walk through sample output: When input is 25 , square root 5.00000 is printed and when input is negative number : -25, then ValueError exception is raised and caught in calling context. 

Notes :- 
 Python support user defined exception.Exceptions should typically be derived from the Exception class, either directly or indirectly. Click here to know how to create user defined exception.

Clean-up actions in python is achieved using try...finally. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. Let's write a sample code to understand use of finally with try statement.
def divide(x, y):
  try:
      result = x / y
  except ZeroDivisionError:
      print "division by zero!"
  else:
      print "result is", result
  finally:
      print "executing finally clause"

divide(12,0)
divide("12","2") #No 'TypeError' exception caught in this case.
Sample output:  On executing divide(12,0 ), finally block is executed after exception ZeroDivisionError is caught.
>>>
division by zero!
executing finally clause
While when divide("12","2" ) is executed, finally block is executed before the exception is re-raised and thrown on console.
>>>
executing finally clause
Traceback (most recent call last):
  File "C:/Python27/clean_finally.py", line 11, in <module>
    divide1("2", "1")
  File "C:/Python27/clean_finally.py", line 3, in divide1
    result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined Clean-up Actions in python is done using with statement. With statement guarantee that resources are closed and placed in pool right after its use, even if execution is failed.In the following code lines, after the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines.
with open("myfile.txt") as f:
    for line in f:
        print line,
Previous:Python input and output  Next:Iterators and Generators

2 Comments

Previous Post Next Post