0% found this document useful (0 votes)
2 views7 pages

3.5 Exception Handling

The document explains the use of try and except statements in Python for handling exceptions, including examples of single and multiple except blocks. It also covers the use of the finally clause, which executes regardless of whether an exception is raised, and how to intentionally raise exceptions. Additionally, it illustrates various scenarios of exception handling with code examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

3.5 Exception Handling

The document explains the use of try and except statements in Python for handling exceptions, including examples of single and multiple except blocks. It also covers the use of the finally clause, which executes regardless of whether an exception is raised, and how to intentionally raise exceptions. Additionally, it illustrates various scenarios of exception handling with code examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

TRY AND EXCEPT STATEMENT - CATCHING EXCEPTIONS

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

a = ["CSBS", "CCE", "IT"]

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:

print ("Index out of range")

OUTPUT

HANDLING AN EXCEPTION - MULTIPLE EXCEPT BLOCKS

try:
You do your operations here;

......................

except ExceptionI:
If there is ExceptionI, then execute this block.

except ExceptionII:

If there is ExceptionII, then execute this block.

......................

else:

If there is no exception then execute this block.

∙ 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

Illustrate use of Multiple except clause

try:

a=int(input("Enter the first number:"))

b=int(input("Enter the second number:"))

c=a/b

print('a = ',a)

print('b = ',b)

print('a/b = ',c)

except ZeroDivisionError:

print("You cannot Divide number by Zero")

except ValueError:
print("Provide int values only")

OUTPUT
Program 18

Write a program use of IOError

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

except IOError:

print("Error: can\'t find file or read data")

else:

print("Written content in the file successfully")

fh.close()

OUTPUT

HOW TO RAISE AN EXCEPTION

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:

raise Exception( "Length is exceed the size ")


TRY WITH ELSE CLAUSE
Only when the try clause fails to throw an exception the Python interpreter goes on to the else

block. Program 20

def find( num1 ):

try:

res = 1 / num1

except ZeroDivisionError:

print( "We cannot divide by zero" )

else:

print ( res )

# Calling the function and passing values

find( 4 )

find( 0 )

THE TRY-EXCEPT-FINALLY BLOCKS- FINALLY KEYWORD IN PYTHON

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.

The finally block sometime referred to as finally clause.

 The finally block consists of the finally keyword.

 The finally block is placed after the last except block.

 The specialty of finally block is it will be executed always irrespective of whether

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:

# This block is optional.

# 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:

# Python interpreter will always execute this code.

Program 21

try:

div = 4 // 0

print( div )

# this block will handle the exception raised

except ZeroDivisionError:

print( "Atepting to divide by zero" )


# this will always be executed no matter exception is raised or not

finally:

print( 'This is code of finally clause' )

OUTPUT

Program 22
L1=[192,"CSE","CCE","CSBS",23.45]

try:

print(L1)

n=int(input("enter the index to reterive the

element")) print('index=',n,'Element=',L1[n])

except IndexError:

print("Please check the index")

print("Index Out of bounds")

finally:

print("No one can stop me from Running!!!")


OUTPUT

Multiple Exceptions in a Single Block


An except clause may name multiple exceptions as a parenthesized tuple

try:
print('10'+10)

print(1/0)

except(TypeError,ZeroDivisionError):

print("Invalid Input")

OUTPUT

You might also like