Type Here to Get Search Results !

Write a program in Python to handle user defined exception

 Write a program in Python to handle user defined exception for given problem


Python has many built-in exceptions which forces your program to output an error

when something in it goes wrong. However, sometimes you may need to create

custom exceptions that serves your purpose.

Write a program in Python to handle user defined exception

A list of common exceptions:

ZeroDivisionError: Occurs when a number is divided by zero.

#totalprogrammingcode

NameError: It occurs when a name is not found. It may be local or global.

IndentationError: If incorrect indentation is given.

IOError: It occurs when Input Output operation fails.

EOFError: It occurs when the end of the file is reached, and yet operations are

being performed.

In Python, users can define such exceptions by creating a new class. This exception

class has to be derived, either directly or indirectly, from Exception class. Most of the

built-in exceptions are also derived from this class.

Example:

def input_age(age):

 try:

 assert int(age) > 18

 except ValueError:

 return 'ValueError: Insert integer value'

 else:

 return 'You are Adult'

output:

>>> print(input_age(25))

You are Adult

>>> print(input_age('abc'))

ValueError: Insert integer value

Exception handling in Python

If the Python program contains suspicious code that may throw the exception, we must

place that code in the try block. The try block must be followed with the except

statement which contains a block of code that will be executed if there is some

exception in the try block.

Example:

try:

 a = int(input("Enter a:"))

 b = int(input("Enter b:"))

 c = a/b;

 print("a/b = %d"%c)

except Exception:

 print("can't divide by zero")

else:

 print("Hi I am else block")

Output:

Enter a:10

Enter b:0

can't divide by zero

Example

1. Write a Python program to Check for ZeroDivisionError Exception


a = int(input("Enter first number : "))
b = int(input("Enter second number : "))

try :
    
    c = a/b 
    
except ZeroDivisionError :
    
    print("\nZero Division Error Occured")


2. Write a Python program to create user defined exception that will check whetherthe password is correct or not? 

password = input("Enter Password : ")

try :
    
    if(password != "chetandagajipatil333") :
        
        raise Exception("Incorrect Password")
        
    else :
        
        print("Correct Password")
except :
    
    raise
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Below Post Ad