0% found this document useful (0 votes)
5 views5 pages

PRG1

The document provides examples of various exceptions in Python, including ValueError, IndexError, NameError, TypeError, and ZeroDivisionError, along with their handling mechanisms. It also discusses custom exception classes for specific error scenarios and demonstrates the use of try-except blocks, finally statements, and raising exceptions. The examples illustrate how to manage errors effectively in Python programming.

Uploaded by

barathkumar9176
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)
5 views5 pages

PRG1

The document provides examples of various exceptions in Python, including ValueError, IndexError, NameError, TypeError, and ZeroDivisionError, along with their handling mechanisms. It also discusses custom exception classes for specific error scenarios and demonstrates the use of try-except blocks, finally statements, and raising exceptions. The examples illustrate how to manage errors effectively in Python programming.

Uploaded by

barathkumar9176
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/ 5

1) A) Exception

i) Value Error

import math
def num_stats(x):
if x is not int:
raise TypeError("Work with Numbers Only")
if x < 0:
raise ValueError("Work with Positive Numbers Only")
print(f'{x} square is {x*x}')
print(f'{x} square root is {math.sqrt(x)}')

OUTPUT :

Program finished with exit code 0


Press ENTER to exit console.

ii) Index Error

import sys
try:
my_list = [3,7, 9, 4, 6]
print(my_list[6])
except IndexError as e:
print(e)

OUTPUT :

List index out of range


...Program finished with exit code 0.
Press ENTER to exit console.

iii) Name Error

def geek_message():
try:
geek= "GeeksforGeeks"
return geeksforgeeks
except NameError:
return "NameError occurred. Some variable isn't defined."
print(geek_message())

OUTPUT :
Program finished with exit code 0
Press ENTER to exit console.
iv) Type Error

geeky_list =["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"]


indices=[0, 1, "2", 3]
for i in range(len(indices)):
try:
print(geeky_list[indices[i]])
except TypeError:
print("TypeError: Check list of indices")

OUTPUT :
Geeky
GeeksforGeeks
TypeError: Check list of indices
Geek
...Program finished with exit code 0
Press ENTER to exit console

v) Divide by zero Error


try:
num1 = int(input("Enter First Number: "))
num2= int(input("Enter Second Number: "))
result = num1/num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)

OUTPUT :
Enter First Number: 3
Enter Second Number: 6
0.5
...Program finished with exit code 0.
Press ENTER to exit console.
B) Exception Handling

class Error(Exception):

"""Base class for other exceptions"""


pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number

number = 10

# user guesses a number until he/she gets it right

while True:
try:
i_num= int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")

OUTPUT :

Enter a number: 9
This value is too small, try again!
Enter a number: 11
This value is too large, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
C) Finally Block

#working of try()
def divide(x, y):
try:
# Floor Division: Gives only Fractional
# Part as Answer
result =x//y
except ZeroDivisionError:
print("Sorry! You are dividing by zero ")
else:
print("Yeah! Your answer is:", result)
finally:
# this block is always executed
# regardless of exception generation.
print("This is always executed')

# Look at parameters and note the working of Program

divide(3,2)
divide(3, 0)

OUTPUT :

YEAH! YOUR ANSWER IS: 1


thisis always executed
YEAH! YOUR ANSWER IS: 0
this is always executed
D) Raise Exception

class Error(Exception):
"""Base class for all exceptions"""
pass

class PasswordSmallError(Error):
"""Raised when the input password is small"""
pass

class PasswordLargeError(Error):
"""Raised when the input password is large"""
pass

try:
password= input("Enter a password")
if len(password) <6:
raise PasswordSmallError("Password is short!")

if len(password) > 15:


raise PasswordLargeError("Password is long!")

except PasswordSmallError as ps:


print(ps)

except PasswordLargeError as pl:


print(pl)

OUTPUT :

ENTER A PASSWORD: rajarajanamjcrrr


PASSWORD IS LONG!

You might also like