PRG1
PRG1
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 :
import sys
try:
my_list = [3,7, 9, 4, 6]
print(my_list[6])
except IndexError as e:
print(e)
OUTPUT :
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
OUTPUT :
Geeky
GeeksforGeeks
TypeError: Check list of indices
Geek
...Program finished with exit code 0
Press ENTER to exit console
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):
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
number = 10
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')
divide(3,2)
divide(3, 0)
OUTPUT :
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!")
OUTPUT :