Search code examples
pythontry-exceptredundancy

Best way to force a try-except to fail (Python)?


I am writing a code that asks users to make two inputs, then will use try: to check that they are both integers, then use an If statement to check that they are both above 0. If either of these conditions is not met then the error 'Positive non zero integers only please.' will show. What would be the best way to have this message show, regardless of the reason it has failed, while only having to write that line once (instead of having another print line after the If statement)? What I have below is a line of random text if the If statement is true, which causes the try: to fail and the code to run the except:

try:
    runs, increment = int(runs), int(increment)
    if (increment == 0):
        print ("I can't increment in steps of 0.")
    elif (increment < 0 or runs <= 0):
        this line has no meaning, and will make the program go to the except: section
except:
    print('Positive non zero integers only please.')

This does what I want but is not really a great solution, so I am just curious if there are any other methods that might work, or should I just put the same print line after the if statement instead? (I cant make separate messages for each failure, because this is a school project so the outputs need to be exactly what we have been given)


Solution

  • What you want is a raise statement:

    try:
        runs, increment = int(runs), int(increment)
        if increment < 1 or runs < 1:
            raise ValueError
    except ValueError:
        print("Positive non zero integers only please.")
    

    Note that int() will raise ValueError if it can't convert the value to an int, so except ValueError should catch either situation. (Having a bare except: that catches unknown errors is a bad habit that can make your code harder to debug; best to break it early!)