Page 207 - Beginning Programming with Pyth - John Paul Mueller
P. 207
1.
2.
Handling a single exception
In Chapter 8, the IfElse.py and other examples have a terrible habit of spitting out exceptions when the user inputs unexpected values. Part of the solution is to provide range checking. However, range checking doesn’t overcome the problem of a user typing text such as Hello in place of an expected numeric value. Exception handling provides a more complex solution to the problem, as described in the following steps.
Open a new notebook.
You can also use the downloadable source file, BPPD_10_Dealing_with_Errors.ipynb.
Type the following code into the notebook — pressing Enter after
each line:
try:
Value = int(input("Type a number between 1 and 10: "))
except ValueError:
print("You must type a number between 1 and 10!")
else:
if (Value > 0) and (Value <= 10):
print("You typed: ", Value)
else:
print("The value you typed is incorrect!")
The code within the try block has its exceptions handled. In this case, handling the exception means getting input from the user by using the int(input()) calls. If an exception occurs outside this block, the code doesn't handle it. With reliability in mind, the temptation might be to enclose all the executable code in a try block so that every exception would be handled. However, you want to make your exception handling small and specific to make locating the problem easier.
The except block looks for a specific exception in this case: ValueError. When the user creates a ValueError exception by typing Hello instead of a numeric value, this particular exception block is executed. If the user were to generate some other exception, this except block wouldn’t handle it.
The else block contains all the code that is executed when the try