Page 216 - Beginning Programming with Pyth - John Paul Mueller
P. 216

 Using a single except clause to handle multiple exceptions works only when a common source of action fulfills the needs of all the exception types. Otherwise, you need to handle each exception individually. The following steps show how to handle multiple exceptions by using a single except clause.
1. 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, KeyboardInterrupt):
                  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!")
Note that the except clause now sports both a ValueError and a KeyboardInterrupt exception. These exceptions appear within parentheses and are separated by commas.
2. Click Run Cell.
Python asks you to type a number between 1 and 10.
3. Type Hello and press Enter.
The application displays an error message (refer to Figure 10-1).
4. Click Run Cell.
Python asks you to type a number between 1 and 10.
5. Choose Kernel ⇒ Interrupt.
This act is akin to pressing Ctrl+C or Cmd+C in other IDEs.
6. Type 5.5 and press Enter.
The application displays an error message (refer to Figure 10-1).
7. Perform Steps 2 and 3 again, but type 7 instead of Hello.
This time, the application finally reports that you’ve provided a
   









































































   214   215   216   217   218