3.5 Exception Handling
3.5 Exception Handling
The try clause contains the code that can raise an exception, while the except clause contains the code
lines that handle the exception.
Program 16
Write a program to store list of elements and display the values using for.
# Python code to catch an exception and handle it using try and except code blocks
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:
OUTPUT
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
......................
else:
∙ A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
∙ You can also provide a generic except clause, which handles any exception.
∙ After the except clause(s), you can include an else-clause. The code in the else-block executes if the
code in the try: block does not raise an exception.
∙ The else-block is a good place for code that does not need the try: block's protection.
Program 17
try:
c=a/b
print('a = ',a)
print('b = ',b)
print('a/b = ',c)
except ZeroDivisionError:
except ValueError:
print("Provide int values only")
OUTPUT
Program 18
try:
fh = open("testfile", "w")
except IOError:
else:
fh.close()
OUTPUT
We can intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.
Program 19
num = [3, 4, 5, 7]
if len(num) > 3:
block. Program 20
try:
res = 1 / num1
except ZeroDivisionError:
else:
print ( res )
find( 4 )
find( 0 )
It is always used after the try-except block. The finally code block is always executed after the try block
has terminated normally or after the try block has terminated for some other reason.
exception is raised or not raised and whether exception is handled or not handled.
Syntax:
try:
# Code block
# These statements are those which can probably have some error
except:
# If the try block encounters an exception, this block will handle it.
else:
# If there is no exception, this code block will be executed by the Python interpreter
finally:
Program 21
try:
div = 4 // 0
print( div )
except ZeroDivisionError:
finally:
OUTPUT
Program 22
L1=[192,"CSE","CCE","CSBS",23.45]
try:
print(L1)
element")) print('index=',n,'Element=',L1[n])
except IndexError:
finally:
try:
print('10'+10)
print(1/0)
except(TypeError,ZeroDivisionError):
print("Invalid Input")
OUTPUT