KEMBAR78
Exceptions | PDF | Computer Engineering | Computer Science
0% found this document useful (0 votes)
8 views12 pages

Exceptions

The document discusses exception handling in Python, demonstrating how to manage errors such as ZeroDivisionError and ValueError through try-except blocks. It illustrates the importance of catching specific exceptions and the order in which they should be handled, as well as the use of user-defined exceptions. Additionally, it provides examples of retrying operations and raising exceptions when certain conditions are met.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

Exceptions

The document discusses exception handling in Python, demonstrating how to manage errors such as ZeroDivisionError and ValueError through try-except blocks. It illustrates the importance of catching specific exceptions and the order in which they should be handled, as well as the use of user-defined exceptions. Additionally, it provides examples of retrying operations and raising exceptions when certain conditions are met.

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

10/5/23, 11:06 AM Exceptions

Exceptions
Code without any exception handlers

In [3]: #%% Without any exception handler

def f(a,b):
print("In fuction-f():")
print("Calling fuction-g():")
z = g(a,b)
print("Completed Division operation Ans:",z,"\t Returning from f().")
return z;

def g(a,b):
print("In fuction-g():")
print("Calling fuction-divideOp():")
z = divideOp(a,b)
print("Completed Division operation Ans:",z,"\t Returning from g().")
return z;

def divideOp(a,b):
z = a/b
print("Completed Division operation Ans:",z,"\t Returning from divideOp.")
return z;

a1 =int(input('Enter a number: '))


b1 =int(input('Enter another number: '))
c1 = f(a1,b1)
print("In Main: Ans:",c1)

Enter a number: 5
Enter another number: 0
In fuction-f():
Calling fuction-g():
In fuction-g():
Calling fuction-divideOp():

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 1/12
10/5/23, 11:06 AM Exceptions

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Input In [3], in <cell line: 25>()
23 a1 =int(input('Enter a number: '))
24 b1 =int(input('Enter another number: '))
---> 25 c1 = f(a1,b1)
26 print("In Main: Ans:",c1)

Input In [3], in f(a, b)


5 print("In fuction-f():")
6 print("Calling fuction-g():")
----> 7 z = g(a,b)
8 print("Completed Division operation Ans:",z,"\t Returning from f().")
9 return z

Input In [3], in g(a, b)


12 print("In fuction-g():")
13 print("Calling fuction-divideOp():")
---> 14 z = divideOp(a,b)
15 print("Completed Division operation Ans:",z,"\t Returning from g().")
16 return z

Input In [3], in divideOp(a, b)


18 def divideOp(a,b):
---> 19 z = a/b
20 print("Completed Division operation Ans:",z,"\t Returning from divid
eOp.")
21 return z

ZeroDivisionError: division by zero

Instead of stopping the execution, the caller of f() wants to retry with new values from the
user.

In [3]: #%% Catching any exception in a try block


def divideOp(a,b):
z = a/b
print("Completed Division operation. Ans:",z)
return z;

def f(a,b):
print("In fuction-f():")
print("Calling fuction-g():")
z = g(a,b)
return z;

def g(a,b):
print("In fuction-g():")
print("Calling fuction-divideOp():")
z = divideOp(a,b)
return z;

while(True):
try:
a1 =int(input('Enter the first number: '))
b1 =int(input('Enter the second number: '))
c1 = f(a1,b1)
print("Completed Division operation. Ans:",c1)
break;
except :
print('Some error occurred. We will ask the user to reenter.')

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 2/12
10/5/23, 11:06 AM Exceptions
print("Outside try block")
print('Program Continues !!! ')

Enter the first number: 5


Enter the second number: 0
In fuction-f():
Calling fuction-g():
In fuction-g():
Calling fuction-divideOp():
Some error occurred. We will ask the user to reenter.
Enter the first number: 5
Enter the second number: 1
In fuction-f():
Calling fuction-g():
In fuction-g():
Calling fuction-divideOp():
Completed Division operation. Ans: 5.0
Completed Division operation. Ans: 5.0
Program Continues !!!

In [4]: #%% Catching any exception in a try block


try:
a=5
b='0'
print(a/b)
print("Completed Division operation")
except :
print('Some error occurred.')

print("Out of try except blocks.")

Some error occurred.


Out of try except blocks.

Catching specific exception in a try block

In [5]: #%% Catching specific exception in a try block


try:
a=5
b=0
print(a/b)
print("Completed Division operation")
except TypeError as e:
print('Invalid data type error occurred. The exception:',e)

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 3/12
10/5/23, 11:06 AM Exceptions

print("Out of try except blocks.")

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Input In [5], in <cell line: 2>()
3 a=5
4 b=0
----> 5 print(a/b)
6 print("Completed Division operation")
7 except TypeError as e:

ZeroDivisionError: division by zero

Catching multiple exceptions in a try block

In [10]: #%% Catching multiple exceptions in a try block


try:
a=5
b='4'
print(a/b)
print("Completed Division operation")
except TypeError:
print('Invalid data type error occurred.')
except ZeroDivisionError as e:
print ('Division by zero not allowed. Exception:',e)

print("Out of try except blocks.")

Invalid data type error occurred.


Out of try except blocks.

In [6]: try:
print("try block")
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 4/12
10/5/23, 11:06 AM Exceptions
print("last statement in try block")
except ZeroDivisionError:
print("Handling ZeroDivisionError block")
print("Division by 0 not accepted")
except:
print("Other than ZeroDivisionError handling")

else:
print("else block is running")
print("Division = ", z)

print("Outside the try block")

try block
Enter a number: 5
Enter another number: 0
Handling ZeroDivisionError block
Division by 0 not accepted
Outside the try block

else block, finally block usage

The except: block is the handler for any kind of exception. Test case 1(positive): 5, 3; Test
case 2 (negative): 5, 0; Test case 3: 5, 'a'

In [7]: ###### %% else block, finally block usage

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 5/12
10/5/23, 11:06 AM Exceptions
try:
print("try block")
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("Handling ZeroDivisionError block")
print("Division by 0 not accepted")
except:
print("Other than ZeroDivisionError handling")

else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )

try block
Enter a number: 5
Enter another number: 0
Handling ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.

When the exception not handled, it is going to terminate the program. Test case: 5, 'a'

In [8]: #%% else block, finally block usage

try:
print("try block")
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("Handling ZeroDivisionError block")
print("Division by 0 not accepted")

else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )

try block
Enter a number: 5
Enter another number: a
finally block
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [8], in <cell line: 3>()
4 print("try block")
5 x=int(input('Enter a number: '))
----> 6 y=int(input('Enter another number: '))
7 z=x/y
8 except ZeroDivisionError:

ValueError: invalid literal for int() with base 10: 'a'

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 6/12
10/5/23, 11:06 AM Exceptions

raising an exception

In [10]: #%% raising an exception

try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")

Enter a number upto 100: 102


102 is out of allowed range

On the command prompt, the following will work properly. (Echo switched off during the
input for password)

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 7/12
10/5/23, 11:06 AM Exceptions

In [1]: import getpass


user = input('Enter User:')
passwd = getpass.getpass('Enter Password:')
print("You entered: ",passwd)

Enter User:admin
Enter Password:········
You entered: welcome1

To make the print function aware of displaying an object state, str(self) method must be
implemented in the class. The function must return a string.

In [9]: dir(Exception)

['__cause__',
Out[9]:
'__class__',
'__context__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__setstate__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__suppress_context__',
'__traceback__',
'args',
'with_traceback']

creating a user defined exception. most of the exception classes in python extends from the
Exception class. You can derive your own exception class either from the Exception class or
from any sublcass of Exception (like ArithmeticError). See exception heirarchy.

In [2]: import getpass

class AuthenticationFailedException(Exception):
"""Base class for authentication failures."""
def __init__(self, message):
self.message = message
def __str__(self):
return "Authentication Failed Due To:"+self.message

class InvalidUser(AuthenticationFailedException):

def __init__(self,user):

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 8/12
10/5/23, 11:06 AM Exceptions
msg = "User:"+user+" Invalid."
AuthenticationFailedException.__init__(self, msg)

class InvalidPassword(AuthenticationFailedException):

def __init__(self):
msg = "Invalid Password:"
AuthenticationFailedException.__init__(self, msg)

def verifyLogin():
user = input('Enter User:')
passwd = getpass.getpass('Enter Password:')
if (user != "admin") :
raise InvalidUser(user)
if (passwd != "welcome1"):
raise InvalidPassword()

#print(dir(Exception))
loginSucceeded = False
while (loginSucceeded == False):
try:
verifyLogin()
print("Login Successful")
loginSucceeded=True

except InvalidUser as e:
print(e)
print("Caught InvalidUser with message:",e.message)

except InvalidPassword as e:
print("Caught InvalidPassword with message:",e.message)

except AuthenticationFailedException as e:
print("Caught AuthenticationFailedException with message:",e.message)

print("\n\nLogin Succeeded!!! \n\nAllowing other activities after login !!!")

#%%

Enter User:xyz
Enter Password:········
Authentication Failed Due To:User:xyz Invalid.
Caught InvalidUser with message: User:xyz Invalid.
Enter User:admin
Enter Password:········
Caught InvalidPassword with message: Invalid Password:
Enter User:admin
Enter Password:········
Login Successful

Login Succeeded!!!

Allowing other activities after login !!!

Order of Exceptions caught is important. The search for exception handler ends when the
first match is found. Subclass is a base class (InvalidUser is an AuthenticationFailedException
and InvalidPassword is an AuthenticationFailedException. When we place the base class
handler followed by subclass halders, the control will always enter the baseclass handler

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 9/12
10/5/23, 11:06 AM Exceptions

only. The following is not the recommended order (The control will never enter InvalidUser
or InvalidPassword blocks)

In [ ]: except AuthenticationFailedException as e:
print("Caught AuthenticationFailedException with message:",e.message)
except InvalidUser as e:
print("Caught InvalidUser with message:",e.message)
except InvalidPassword as e:
print("Caught InvalidPassword with message:",e.message)

The following is the recommended order. The control will first try for a match with specific
subclasses (InvalidUser or InvalidPassword), when they did not match it is handled by base
class (AuthenticationFailedException)

In [ ]: except InvalidUser as e:
print("Caught InvalidUser with message:",e.message)
except InvalidPassword as e:
print("Caught InvalidPassword with message:",e.message)
except AuthenticationFailedException as e:
print("Caught AuthenticationFailedException with message:",e.message)

main calls f(), f() calls g(), g calls divideOp(). Exception occurred in divideOp() and error
handling done in g()

In [4]: def divideOp():


a =int(input('Enter the first number: '))
b =int(input('Enter the second number: '))
z = a/b
print("Completed Division operation. Ans:",z)
return z;

def f():
print("In fuction-f():")
print("Calling fuction-g():")
z = g()
print("Other Steps in f.")
return z;

def g():
print("In fuction-g():")
print("Calling fuction-divideOp():")
try:

z = divideOp()
print("Completed Division operation.")

except :
print('Some error occurred. Fixing the problem in g by setting the result t
z = -1
print("Other Steps in g.")
return z;

print("Main section calling f():")


c1 = f()
print("Answer:",c1)
print('Program Continues !!! ')

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 10/12
10/5/23, 11:06 AM Exceptions
Main section calling f():
In fuction-f():
Calling fuction-g():
In fuction-g():
Calling fuction-divideOp():
Enter the first number: 5
Enter the second number: 0
Some error occurred. Fixing the problem in g by setting the result to -1.
Other Steps in g.
Other Steps in f.
Answer: -1
Program Continues !!!

main calls f(), f() calls g(), g calls divideOp(). Exception occurred in divideOp() and error
handling done in f()

In [6]: def divideOp():


a =int(input('Enter the first number: '))
b =int(input('Enter the second number: '))
z = a/b
print("Completed Division operation. Ans:",z)
return z;

def f():
print("In fuction-f():")
print("Calling fuction-g():")
try:

z = g()
print("Completed Division operation.")

except :
print('Some error occurred. Fixing the problem in f by setting the result t
z = -1
print("Other Steps in f.")
return z;

def g():
print("In fuction-g():")
print("Calling fuction-divideOp():")

z = divideOp()
print("Other Steps in g.")
return z;

print("Main section calling f():")


c1 = f()
print("Answer:",c1)
print('Program Continues !!! ')

Main section calling f():


In fuction-f():
Calling fuction-g():
In fuction-g():
Calling fuction-divideOp():
Enter the first number: 5
Enter the second number: 0
Some error occurred. Fixing the problem in f by setting the result to -1.
Other Steps in f.
Answer: -1
Program Continues !!!

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 11/12
10/5/23, 11:06 AM Exceptions

In [ ]:

localhost:8888/nbconvert/html/pythonlab/lab3/Exceptions.ipynb?download=false 12/12

You might also like