Page 221 - Beginning Programming with Pyth - John Paul Mueller
P. 221
FIGURE 10-8: Providing usable input results in a usable output.
Nested exception handling
Sometimes you need to place one exception-handling routine within another in a process called nesting. When you nest exception-handling routines, Python tries to find an exception handler in the nested level first and then moves to the outer layers. You can nest exception- handling routines as deeply as needed to make your code safe.
One of the more common reasons to use a dual layer of exception- handling code is when you want to obtain input from a user and need to place the input code in a loop to ensure that you actually get the required information. The following steps demonstrate how this sort of code might work.
1. Type the following code into the notebook — pressing Enter after
each line:
TryAgain = True
while TryAgain:
try:
Value = int(input("Type a whole number. "))
except ValueError:
print("You must type a whole number!")
try:
DoOver = input("Try again (y/n)? ")
except:
print("OK, see you next time!")
TryAgain = False
else:
if (str.upper(DoOver) == "N"):