Write A Python Program To Implement Zero Division Error Exception Using User Defined Exception

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Implement Zero Division Error Exception Using User Defined Exception

 

Title : 

Write A Python Program To Implement Zero Division Error Exception Using User Defined Exception


Write A Python Program To Implement Zero Division Error Exception Using User Defined Exception


 

Description : 

Hi in this article we define a new user defined class named DivisionByZeroError that will inherit the Exception class and then pass it. This is the method to define a user defined exception.


    
class DivisionByZeroError(Exception):
   pass

    


In the main program we use try block, take two variables and ask the user to enter floating point numbers. Using the if statement check if the denominator is zero then raise the division by zero exception that we had defined above. Else perform the division operation and print the result. Use the exception to catch the divided by zero error and print the appropriate message that was raised.


    
try:
   num1 = float(input("Enter first number: "))
   num2 = float(input("Enter second number: "))
   if num2 == 0:
       raise DivisionByZeroError("Cannot divide by zero")
   else:
       result = num1 / num2
       print("Result:", result)
except DivisionByZeroError as e:
   print("Error:", e)

    




Complete Python Code : 


    
class DivisionByZeroError(Exception):
   pass

try:
   num1 = float(input("Enter first number: "))
   num2 = float(input("Enter second number: "))
   if num2 == 0:
       raise DivisionByZeroError("Cannot divide by zero")
   else:
       result = num1 / num2
       print("Result:", result)
except DivisionByZeroError as e:
   print("Error:", e)

    

 

 

Output : 


    
Enter first number: 100
Enter second number: 20
Result of division is : 5.00


    

 

Output : 


    
Enter first number: 23
Enter second number: 0
Error: Cannot divide by zero

    



Conclusion :

The above Python program Define say class i.e, a user defined class named as divide by zero error, inside the class it just uses the pass statement. So in the main program we use the try block to ask the user to enter numbers and use the if statement to check if the denominator is zero then reason divide by zero exception. else proceed for division operation. We use the except block to catch the divide by zero exception and print the appropriate message that was raised by the try block. Comment it down below if you have any query is regarding the above Python program and also suggestions to improve the above Python program

 

Post a Comment

0 Comments