Categories

Dec 19, 2019 in Python
Q: How Do You Raise Exceptions For A Predefined Condition In Python?

1 Answer

Dec 19, 2019
We can raise an exception based on some condition.

For example, if we want the user to enter only odd numbers, else will raise an exception.

# Example - Raise an exception

while True:

    try:

        value = int(input("Enter an odd number- "))

        if value%2 == 0:

            raise ValueError("Exited due to invalid input!!!")

        else:

            print("Value entered is : %s" % value)

    except ValueError as ex:

        print(ex)

        break

The output is:

Enter an odd number- 2

Exited due to invalid input!!!

Enter an odd number- 1

Value entered is : 1
Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
May 16 in Python
Dec 22, 2019 in Python
Dec 19, 2019 in Python
...