Advertisement



< Prev
Next >



Python - Multiple Except blocks





So far, we have only seen one except block associated with a try block, where this except block is used to catch a specific type of exception, unless it is declared with the Exception class, which is a superclass of all built-in exception classes and could catch various types of subclass exceptions.

In this article, we are going to understand how it is also possible to have multiple except blocks associated with one try block and how we could create an except block which could catch multiple types of exceptions(without having to declare it with the Exception class).




Why multiply blocks are useful?


In exception hierarchy, the Exception class is the superclass of all built-in non-system exiting exception classes and could be used to catch various types of its subclass exceptions(except system exiting exception classes, which are inherited by BaseException exception class).

Though by declaring an Exception class in except block, we could catch various types of its subclass exceptions, sometimes we would like to catch a specific type of exception and work accordingly. For this reason, we use multiple except blocks, where each except block would catch a specific type of exception.




Multiple except blocks example


#Python - Multiple except blocks with one try block

try:
    #Creating a list in Python
    arr = [1,2,3,4]

    #trying to access an invalid 5th index in a list, hence IndexError Exception
    print('value = ',arr[5])
	
#except block to catch ArithmeticError exception	
except ArithmeticError as e:    
    print('ArithmeticError exception caught - ',e)

#except block to catch IndexError exception
except IndexError as e:   	
    print('IndexError exception caught -',e)
	
#except block to catch Exception exception
except Exception as e:	
    print('Exception exception caught - ',e)
	


Output is -:


IndexError exception caught - list index out of range

In this code, we have three except blocks associated with one try block. At the runtime, the code in the try block raises an exception of type IndexError exception, this exception type is matched with the declared exception type in every except block(matching starts with the first except block).


The except block that matches with the type of raised exception is executed, while the rest of except blocks are skipped. Let's see how -




Advertisement




Placement of an except block is very important


In case of multiple except blocks, the except block declared with a specific subclass exception class must always be placed above the except block declared with a less specific/general superclass exception class, otherwise the except block declared with, let's say the Exception class will catch various types of its subclass exceptions and its underneath except block declared with a specific subclass exception will not be reached and executed.



Let's understand this by an example -
#Python - Multiple except blocks with one try block example

try:
    #Creating a list in Python
    arr = [1,2,3,4]

    #trying to access an invalid 5th index in a list, hence IndexError Exception
    print('value = ',arr[5])
	

#except block to catch Exception exception
except Exception as e:	
    print('Exception exception caught - ',e)


#except block to catch IndexError exception
except IndexError as e:   	
    print('IndexError exception caught -',e)


Output


Exception exception caught -  list index out of range




The script raises an exception of type IndexError, this exception will be always be caught by the first except block, because the Exception class is a superclass of IndexError exception class.

Hence, the second except block declared with matching exception type IndexError will not be reachable or executed even when the exception raised has a specific match to its declared type.

That's why, the except block declared with a specific exception type, for example - IndexError class, must be placed above the except block declared with a general type Exception class, proving the value of placement of an except block in the multiple except blocks scenario.





# Python - finally block example

import sys

try:
	a = 'five'
	ab = a + 2
	
except (NameError, TypeError, Exception) as e:
	print("Exception caught - ",e)
	
	# This function gives the name of caught exception which was thrown by try block 
	print(sys.exc_info())
	
finally:
	print("A finally block executes with or without exception")


Output is -:


Exception caught -  can only concatenate str (not "int") to str
(, TypeError('can only concatenate str (not "int") to str'), )
A finally block executes with or without exception

In this code, we have declared an except block(associated with a try block) which could catch three types of exceptions i.e. NameError, TypeError, Exception. At the runtime, the code in try block raises an exception of type NameError exception, this exception type is matched with one of the declared exception types in the except block.



Note :


Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement