[Tutor] Exception not working as expected?

Chip Wachob wachobc at gmail.com
Thu Feb 28 16:03:08 EST 2019


Hello,

Python 2.7 & Windows and also Linux are the platforms being used.  Running
the code from the command line / terminal as   python except.py.  Note that
it does work properly in Linux.  So I'm guessing I need to test for a
different exception along with the KeyboardInterrupt??

So, the code below is my example.

When I run it, everything is fine until I attempt to test the
KeyboardInterrupt exception.

When I do this, the traceback is as follows:
Traceback (most recent call last):
  File "except.py", line 71, in <module>
    start_menu()


What I was expecting was the message in the exception to be displayed ("
Keyboard Interrupt - Exiting "), then for the program to exit gracefully.

I'm sure that this is a NOOB mistake, but I can't seem to figure out why
the exception isn't being trapped and handled the way I had hoped.

Can someone shed some light on this for me?

Thank you,




# import standard libraries
import os
import time
import sys

DISPLAY_TIME = 5
g_user_num_items = -1

def start_menu():

    start_quit = False

    os.system('cls' if os.name == 'nt' else 'clear')

    print "\n\n\n\n Welcome to Test.\n"
    time.sleep(DISPLAY_TIME)

    try:
        while not start_quit:

            os.system('cls' if os.name == 'nt' else 'clear')

            print "\n +++ Test Start Menu +++"
            print "Enter the number of items to test,"
            print "or, 0 for individual testing."
            print "Then press <Enter>\n"

            # wait for it...
            num_items = int(raw_input(": "))

            if num_items == 0: # individual testing
                print "\nIndividual testing requested"
                g_user_num_items = num_items
                start_quit = True

            elif(num_items >= 1 and num_items <= 512):   # multi testing
                g_user_num_items = num_items
                print "\nItem count of ", g_user_num_items, ", accepted!"
                start_quit = True

            else:   # unexpected input eg A, >, ? etc
                print " Invalid number of items, please re-enter"

            time.sleep(DISPLAY_TIME / 2)

    ##### end item count input

    # detect ctrl-c
    except KeyboardInterrupt:
        # provides a clean exit
        print "\n\n Keyboard Interrupt - Exiting \n\n"
        time.sleep(5)

    # trap no choice, just Enter key cases
    except ValueError:
        # handles non-entry selections like 'Enter'
        print "Invalid selection please try again"
        time.sleep(DISPLAY_TIME / 2)
        start_menu()

    return
##### end main menu


##############################################
# Main entry point into program
#

if __name__ == "__main__":

    start_menu()

    print "End of Script\n"


More information about the Tutor mailing list