Advertisement
#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)
IndexError exception caught - list index out of range
Advertisement
#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)
Exception exception caught - list index out of range
except (Exception1, Exception2, Exception3 .... ExceptionN)
# 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")
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
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement