Great! Naturally, when an exception is thrown, we can do more than just print a custom error message. Consider this example:
x = int(input('Provide a number: '))
print('That is not a number! Try again. ')
In the example above, we ask the user to provide a number using the
input() function within a
while True loop.
input() provides a string from the user, so we want to convert it to a number using
int(). Python Documentation states that
int() throws a
ValueError exception if the argument can't be converted to an integer.
In our case, two options are possible:
int() converts user input successfully, the next line of code is executed, which is
break: we escape the otherwise infinite while loop.
int() fails and throws a
try block is immediately interrupted. Then,
break is never executed. Instead, the
except block prints an error message, and the whole loop repeats in another iteration.