Hi Guys, welcome to my blog in this article you will learn about how to Design A Python Program Which Will Throw User Defined Exception If The Value Entered By User Is Less Than Zero
Title :
Design A Python Program Which Will Throw User Defined Exception If The Value Entered By User Is Less Than Zero
Description :
Define a class named as below zero error and inherit the exception class. In the body of the class just use the pass statement, this the example of a user defined exception.
class BelowZeroError(Exception):
pass
Now in order to use the above exception use the try block. inside the triblock ask user to enter a number and then convert it into an integer value Use the if statement to check if the number is below zero if so raise that below zero error exception by passing a user friendly message string. Use the expect block to catch the exception and a message, using the print function print the exception message.
try:
num = int(input("Enter a number: "))
if num < 0:
raise BelowZeroError("Value is less than or equal to zero")
else:
print("You entered:", num)
except BelowZeroError as e:
print("Error:", e)
Complete Python Code :
class BelowZeroError(Exception):
pass
try:
num = int(input("Enter a number: "))
if num < 0:
raise BelowZeroError("Value is less than or equal to zero")
else:
print("You entered:", num)
except BelowZeroError as e:
print("Error:", e)
Output :
Enter a number: -5
Error: Value is less than or equal to zero
Output :
Enter a number: 9
You entered: 9
Conclusion :
The above Python program users a user defined exception where it checks if the value entered by the user is below zero or not.
If the value entered by the user is below zero it Rises and exception with a user friendly message.
Comment it down below if you have any query is regarding the above Python program and also suggestions to improve the above Python program
0 Comments