Skip to content

Python raise ValueError

  • by

Use raise keyword to raise ValueError in Python. You can wrap the portion of code that you want to be able to catch errors in.

try:
    input(...)
    [...]
except ValueError as e:
    print(e)

Or you can validate the string before converting it:

if not newNumbers.isdecimal():
    print('Not a valid number: ' + s)
raise ValueError('could not find %c in %s' % (ch,str))

Python raise ValueError

Simple example code Raising a ValueError in an if statement.

s = 'bababa'
ch = 'k'
if ch in s.text:
raise ValueError('could not find %c in %s' % (ch, s))

Output:

Python raise ValueError

How to use raise ValueError?

Answer: You have to catch your Error in the except block or your script will stop running at your first raise ValueError().

def isitDoubleorSingle(value):
    try:
        if(value%2!=0):
            raise ValueError()
    except ValueError:
            print(f"Number {value} isn't double")

my_list=[10,22,79,43,11,80]

for x in my_list:
    isitDoubleorSingle(x)

Source: https://stackoverflow.com/questions/73101459/

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *