try...except...else

The try...except...else block is especially useful when we want a certain block of code to be executed only when no exceptions are raised. In order to demonstrate this concept, let's rewrite the guessing game example using this block:

try:
input_value = int(value)
except ValueError as error:
print("The value is invalid %s" % error)
else:
if input_value < 0 or input_value > 9:
print("Input invalid. Enter a number between 0 and 9.")
elif input_value == rand_num:
print("Your guess is correct! You win!")
break
else:
print("Nope! The random value was %s" % rand_num)

The modified guessing game example that makes use of the try...except...else block is available for download along with this chapter as try_except_else.py. In this example, the program compares the user input against the random number only if a valid user input was received. It otherwise skips the else block and goes back to the top of the loop to accept the next user input. Thus, try...except...else is used when we want a specific code block to be executed when no exceptions are raised due to the code in the try block.