in Python by
How Do You Raise Exceptions For A Predefined Condition In Python?

1 Answer

0 votes
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:


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

        if value%2 == 0:

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


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

    except ValueError as ex:



The output is:

Enter an odd number- 2

Exited due to invalid input!!!

Enter an odd number- 1

Value entered is : 1

Related questions

0 votes
asked May 16, 2020 in Python by Robindeniel
0 votes
asked Jun 28, 2020 in Python by Robindeniel