0% found this document useful (0 votes)
121 views

Python Assignment 5 - 18700219054 - Avirup Ray

The document contains 8 code examples demonstrating the use of exceptions in Python. The examples show how to raise different types of exceptions, handle exceptions using try-except blocks, and ensure cleanup code runs using finally blocks. Exceptions are raised and handled for issues like division by zero, invalid input, negative numbers, and custom exception types defined as classes.

Uploaded by

Avirup Ray
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

Python Assignment 5 - 18700219054 - Avirup Ray

The document contains 8 code examples demonstrating the use of exceptions in Python. The examples show how to raise different types of exceptions, handle exceptions using try-except blocks, and ensure cleanup code runs using finally blocks. Exceptions are raised and handled for issues like division by zero, invalid input, negative numbers, and custom exception types defined as classes.

Uploaded by

Avirup Ray
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

1) Write a program that will compute the quotient from two numbers given by the user.

If the denominator is zero, then raise ZeroDivisionError.


If appropriate number is not entered, then raise ValueError.

try:
    a = float(input("Enter number 1 : "))
    b = float(input("Enter number 2 : "))
    q = a/b
    print("Quotient = ",q)
    
except ZeroDivisionError as msg:
    print("Zero Division Error ")
    print("Error Message = ",msg)
    
except ValueError as msg:
    print("Value Error ")
    print("Error Message = ",msg)
F:\>py "test.py"
Enter number 1 : 12
Enter number 2 : we
Value Error
Error Message = could not convert string to float: 'we'

F:\>py "test.py"
Enter number 1 : 10
Enter number 2 : 0
Zero Division Error
Error Message = float division by zero

2) Write a program that prompts the user to enter a number and prints its square. If no
number is entered, KeyboardInterrupt exception is generated.

import math

try:
    a = float(input("Enter number : "))
    sqroot = math.sqrt(a)
    print("Square Root of number = ",sqroot)
    
except KeyboardInterrupt as msg:
    print("Keyboard Interrupt ")
    print("Error Message = ",msg)
    
except:
    print("An Error Occured!!!")
3) Write a program to depict the use of else clause with try-except statement.

try:
    print("Try Block Executed")
    print(20/0)
except:
    print("Except Block Executed")
else:
    print("Else Block...Iam executed if try block contains no exceptions...Ding 
Ding")
finally:
    print("Finally block always executed")

F:\>py "test.py"
Try Block Executed
Except Block Executed
Finally block always executed

4. Write a program that prompts the user to enter a number. If the number is positive or
zero print it, otherwise raise an exception.

class number_is_negative_exception(Exception):
    def __init__(self,arg):
        self.msg = arg
        
a = int(input("Enter Number : "))

if (a>=0):
    print("The number is = ",a)
else:
    raise number_is_negative_exception("Sorry You cant enter a negative number")

5. Write a number game program. Ask the user to enter a number.


If the number is greater than the number to be guessed, raise a ValueTooLarg exception.
If the value is smaller the number to be guessed then raise a ValueTooSmall exception
and prompt the user to enter again.
Quit the program only when the user enters the correct number.
class ValueTooLarge(Exception):
    def __init__(self,arg):
        self.msg = arg
        
class ValueTooSmall(Exception):
    def __init__(self,arg):
        self.msg = arg
        
        
guess = 15
value = int(input("Enter Your Value : "))

while (True):
    try:
        if (value>guess):
            raise ValueTooLarge("Value is too Large")
            
        elif (value<guess):
            raise ValueTooLarge("Value is too Small")
           
        else:
            print("Correct Value Entered")
            break
            
    except ValueTooLarge as msg:
        print("Error message = ",msg)
        value = int(input("Enter Your Value : "))
        continue
        
    except ValueTooSmall as msg:
        print("Error message = ",msg)
        value = int(input("Enter Your Value : "))
        continue
6. Write a program which infinitely prints natural numbers.
Raise the StopIteration exception after displaying first 25 numbers to exit from the
program. Use finally.

class StopIterationException(Exception):
    def __init__(self,arg):
        self.msg = arg

i = 1
while True:
    try:
        if(i<=25):
            print(i)
            i = i+1
        else:
            raise StopIterationException("Given value 25 exceeded")
            
    except StopIterationException as msg:
        print("An Error has ocurred")
        print("Error message = ",msg)
        break
        
    finally:
        print("Finally Block Executed")
F:\>py "test.py"
1
Finally Block Executed
2
Finally Block Executed
3
Finally Block Executed
4
Finally Block Executed
5
Finally Block Executed
6
Finally Block Executed
7
Finally Block Executed
8
Finally Block Executed
9
Finally Block Executed
10
Finally Block Executed
11
Finally Block Executed
12
Finally Block Executed
13
Finally Block Executed
14
Finally Block Executed
15
Finally Block Executed
16
Finally Block Executed
17
Finally Block Executed
18
Finally Block Executed
19
Finally Block Executed
20
Finally Block Executed
21
Finally Block Executed
22
Finally Block Executed
23
Finally Block Executed
24
Finally Block Executed
25
Finally Block Executed
An Error has ocurred
Error message = Given value 25 exceeded
Finally Block Executed

7. Write a program that randomly generates a number. Raise a user-defined exception if


the number is below 0.5 value. Use finally.

import random

class hattori_exception(Exception):
    def __init__(self,arg):
        self.msg = arg
        
a = random.random() # Generating a random number

if (a>=0.5):
    print("The number is = ",a)
else:
    try:
        raise hattori_exception("Sorry the number is less than 0.5 ")
    except hattori_exception as msg:
        print("Error Occurred")
        print("Error Messge = ",msg)
    finally:
        print("Finally Block executed no matter what happens..Ding..Ding!!")
8. Write a program that validates name and age as entered by the user to determine
whether the person can cast vote or not. Use finally

class age_exception(Exception):
    def __init__(self,arg):
        self.msg = arg
        
name = input("Enter your name : ")
age = int(input("Enter your age : "))

if (age>=18):
    print("Dont Worry...You are allowed to vote")
else:
    try:
        raise age_exception("Sorry You are too young to vote ")
    except age_exception as msg:
        print("Error Occurred")
        print("Error Message = ",msg)
    finally:
        print("Finally Block executed no matter what happens..Ding..Ding!!")
        
        
        
    

You might also like