Exception handling is very important in programming. It allows an executing program to not terminate immedialtely after an exception occurs at any point.Let us see how to handle exception in Python. As I have not decribed the whole concept here that is why I have commented the lines. You can also visit Errors and Execptions and read it more clearly.
"""
created_at : 09 Feb 2017.
updated_at : 11 Feb 2017.
aim of script : To understand the concept of exception handling in Python.
coded by : Rishikesh Agrawani.
Python version : 2.7.12
"""
a = 3
b = 4
name = 'Randy'
try:
print a+b #It will get executed
except:
print "Error while adding 2 numbers"
try:
print a+name #It raises TypeError
except:
print "Error while adding 2 numbers" #It will get executed
cities = ["Raipur", 'Jagdalpur', 'Kondagaon', 'Dhamtari', "Nagri"]
try:
for index in range(len(cities)):
print cities[index] #It will get executed to print all the cities
except:
print "Operation successful"
try:
for index in range(len(cities)+1):
print cities[index]
except:
print "Error while accessing the out of range index" #It will get executed
try:
print 5+"Robinson"
except:
print "Can't add integer and string" #It will get executed
finally:
print "finally block execution is fixed" #It will definitely execute
Let us look at a different flavour of handling exceptions. After that we will move towards the advance exception handling examples.Here we wll handle the exact Exception types. Let us see it in the following examples.
#Example 1 - ZeroDivisionError
try: a = 10 c = 0 print a/c #This statement will raise ZeroDivisionError except ZeroDivisionError: #This block will catch the Exception print "You are trying to divide something by 0 (zero)" #So it will execute#Interactive mode programming
>>> a = 10 >>> b = 5 >>> >>> print a 10 >>> print a+b 15 >>> print a/b 2 >>> print a/0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: integer division or modulo by zero >>>
#Example 2 - TypeError
try: a = 10 name = "Peter" print a+name #This statement will raise TypeError except TypeError: print "You are trying to add invalid operands type" #It'll execute#Interactive mode programming
>>> print [1,2,3,4,5] [1, 2, 3, 4, 5] >>> >>> print tuple([1,2,3,4,5]) (1, 2, 3, 4, 5) >>> >>> print tuple({'name':'Rishikesh','age':24,'languages':['C','C++','Python','Go','HTML','JavaScript']}) ('languages', 'age', 'name') >>> >>> print tuple(range(10)) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) >>> >>> print tuple("Rishikesh") ('R', 'i', 's', 'h', 'i', 'k', 'e', 's', 'h') >>> >>> tuple(5+5j) Traceback (most recent call last): File "", line 1, in TypeError: 'complex' object is not iterable >>>
#Example 3 - ValueError
a = int("1234") #Converting '1234', a string to an integer print a try: b = int("1234y") #It will raise ValueError except ValueError: print "You are trying to convert an invalid string equivalent of integer to int type" #it will execute#Interactive mode programming
>>> int('1234') 1234 >>> >>> int('1234y') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '1234y' >>>
#Example 4 - NameError
try: a = 10 b = 5 print a+b #It will print 15 print d except NameError: print "You are trying to access undefined variable(s)" #It will get executed#Interactive mode programming
>>> a = 10 >>> b = 5 >>> >>> print a+b 15 >>> >>> print d Traceback (most recent call last): File "", line 1, in NameError: name 'd' is not defined >>>
Let us move little forward and see how to catch an exception as an object and print the details/information it holds. It is clear in the following example.
#Example 5 - IndexError
try: fruits = ["Apple", "Orange", "Grape", "Blackberry", "Gooseberry", "Strawberry"] #valid indexes are 0,1,2,3,4,5 print fruits[4], fruits[5] #Gooseberry Strawberry print fruits[6] #It will raise IndexError except IndexError as index_err: print "You are trying to access invalid index" print index_err #list index out of range#Interactive mode programming
>>> evens = [num for num in range(2,21) if num%2==0] #A shorthand way to create a list of evens >>> print evens [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] >>> >>> print len(evens) 10 >>> >>> print evens[0] #first element of the list 2 >>> >>> print evens[9] #last element of the list 20 >>> >>> print evens[10] #out of range access Traceback (most recent call last): File "", line 1, in IndexError: list index out of range >>>
#Example 6 - AttributeError
class Details: def __init__(self,name,age,friends): self.name = name self.age = age self.friends = friends def show_details(self): print "Name : ",self.name print "Age : ",self.age print "Friends : ",self.friends #The items are in alphabetical order try: myself = Details("Rishikesh Agrawani",24,["Amit", 'Anand', 'Darshan', 'Guru', 'Pradeep', 'Praja', 'Pratik', 'Shivesh','Vinit']) myself.show_details() #It will get executed except: print "You are accessing the non-attribute." try: print myself.name #It's ok print myself.profession #It will raise an exception except AttributeError as attrib_err: print attrib_err #It will get executed. Details instance has no attribute 'profession'#Interactive mode programming
>>> class Car: ... def __init__(self,name,color,price,is_new): ... self.name = name ... self.color = color ... self.price = price ... self.is_new = is_new ... def show_details(): ... print "Name : ",self.name ... print "Color : ",self.color ... print "Price : ",self.price ... print "IsNew : ",self.is_new ... >>> maruti = Car("Maruti","Red",2000000,True) >>> print "My car's name is : ",maruti.name My car's name is : Maruti >>> >>> print "It's color is : ",maruti.color It's color is : Red >>> >>> print "It's price is : ",maruti.price It's price is : 2000000 >>> >>> print "Is it new : ",maruti.is_new Is it new : True >>> >>> print maruti.gears #It will raise an Exception Traceback (most recent call last): File "", line 1, in AttributeError: Car instance has no attribute 'gears' >>>
Till now, we only focused on the try-except blocks(clauses). Apart from this, try-except statement has 2 other optional clauses. These are else clause & finallly clause.Let us see these clauses in the following examples
The main usage of else block is to put the error free code(that follows the code inside try clause) inside it. In this way we can reduce the number of lines present inside the try clause.
The finally block is used to define the clean up codes. For example, closing the opened files, releasing the netwok connections etc.
#Example 7 - UnboundLocalError (try-except-else-finally clauses)
try:
n1 = 10 #Assigning a value to any variable a way of defining/redefining the variable in that scope
n2 = 5
print n1, n2 #It will be printed
except:
print "An error occured"
else:
print "No error\n" #It will get executed
try:
def print_num():
n1+=1
print n1
print_num() #It will raise an exception
except UnboundLocalError as unbound_err:
print "Either you are trying to access any local variable defined in other suite or an undefined variable."
print unbound_err #local variable 'n1' referenced before assignment
else:
print "Just silent" #It won't get executed
#Interactive mode programming
>>> a = 10
>>> b = 5
>>>
>>> print a
10
>>> print b
5
>>>
>>> def show1():
... print a
... print b
... print id(a)
...
>>> show1()
10
5
140328992554976
>>>
>>> print id(a)
140328992554976
>>>
>>> def show2():
... a+=1
... print a
...
>>> show2()
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in show2
UnboundLocalError: local variable 'a' referenced before assignment
>>>
In previous examples, we saw that we are handling only single exception in each example. So what about there's a possibility of multiple exceptions. Python also has the great technique for this. Let us see how to specify multiple exceptions in except clause.
#Example 8 - KeyboardInterrupt, ValueError, ZeroDivisionError
def test_func(b,s):
try:
d = raw_input('\n\nINPUT : Enter any info Or press Ctrl+c or Command+c to raise KeyboardInterrupt Exception : ')
a = 10
print a/b #If b equals 0
c = int(s) #It will raise an exception, if scontains non-digits
except (ValueError,KeyboardInterrupt,ZeroDivisionError):
print "\nMSG : Either ValueError, KeyboardInterrupt, ZeroDivisionError Exception occured... "
else:
print "No error occured"
finally:
print "This is the last statement(residing inside finally clause) to be executed from try-except-else-finally clauses"
test_func(5,"1235") #It will not raise any exception, so else clause will execute if you don't press Ctrl+c/Command+c
test_func(0,"1235") #ZeroDivisionError will be raised by this statement if you don't press Ctrl+c/Command+c
test_func(5,"1235abc") #ValueError will be raised by this statement if you don't press Ctrl+c/Command+c
In the previous example, it is not clear that which function call is raising which exception because we have defined the Exceptions collectively inside a tuple of except statement.
Let us find the type of exceptions separately and generate the meaningful messages to the user. For the sake of simplicity, I am using the previous example here.
#Example 8 - KeyboardInterrupt, ValueError, ZeroDivisionError (modified)
def test_func(b,s):
try:
d = raw_input('\n\n>>> Enter any info Or press Ctrl+c or Command+c to raise KeyboardInterrupt Exception : ')
a = 10
print a/b #If b equals 0
c = int(s) #It will raise an exception, if s contains non-digits
except ValueError:
print "\nMSG : ValueError Exception occured... "
except KeyboardInterrupt:
print "\nMSG : KeyboardInterrupt Exception occured... "
except ZeroDivisionError:
print "\nMSG : ZeroDivisionError Exception occured... "
else:
print "No error occured"
finally:
print "This is the last statement(residing inside finally clause) to be executed from try-except-else-finally clauses"
test_func(5,"1235") #It will not raise any exception, so else clause will execute if you don't press Ctrl+c/Command+c
test_func(0,"1235") #ZeroDivisionError will be raised by this statement
test_func(5,"1235abc") #ValueError will be raised by this statement