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

The only difference between this example and the previous example is that the except clause doesn’t have the ValueError exception specifically associated with it. The result is that this except clause will also catch any other exception that occurs.
2. Click Run Cell.
You see the error message shown in Figure 10-3. Python automatically detects that you have placed the exception handlers in the wrong order. (You discover more about this issue in the “Handling more specific to less specific exceptions” section later in the chapter.) Reverse the order of the two exceptions so that they
appear like this:
               try:
                  Value = int(input("Type a number between 1 and 10: "))
               except ValueError:
                  print("You must type a number between 1 and 10!")
               except:
                  print("This is the generic error!")
               else:
                  if (Value > 0) and (Value <= 10):
                     print("You typed: ", Value)
                  else:
                     print("The value you typed is incorrect!")
3. Click Run Cell.
Python asks you to type a number between 1 and 10.
4. Type Hello and press Enter.
The application displays an error message (refer to Figure 10-1). When the exceptions are in the right order, the code detects specific errors first and then uses less specific handlers only when necessary.
5. Click Run Cell.
Python asks you to type a number between 1 and 10.
6. Choose Kernel ⇒ Interrupt.
This act is akin to pressing Ctrl+C or Cmd+C in other IDEs. However, nothing actually appears to happen. Look at the server window,however,andyouseeaKernel Interruptedmessage.
7. Type 5.5 and press Enter.
You see the generic error message shown in Figure 10-4 because Notebook is reacting to the interrupt, rather than the incorrect input; the reason is that the interrupt came first. Python queues errors in
    









































































   209   210   211   212   213