This recipe shows how to trap the KeyboardInterrupt and EOFError Python exceptions so that they do not crash your program. As a vehicle to show this, it uses a small Python utility that shows the ASCII code for any ASCII character you type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from __future__ import print_function
"""
char_to_ascii_code.py
Purpose: Show ASCII code for a given character, interactively,
in a loop. Show trapping of KeyboardInterrupt and EOFError exceptions.
Author: Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
"""
print("This program shows the ASCII code for any given ASCII character.")
print("Exit the program by pressing Ctrl-C or Ctrl-Z.")
print()
while True:
try:
c = raw_input( \
"Enter an ASCII character to see its ASCII code: ")
if len(c) != 1:
print("Error: need a string of length 1; retry.")
continue
print("Character:", c)
print("Code:", ord(c))
except KeyboardInterrupt as ki:
print("Caught:", repr(ki))
print("Exiting.")
break
except EOFError as eofe:
print("Caught:", repr(eofe))
print("Exiting.")
break
|
Without the handling of these two exceptions, KeyboardInterrupt and EOFError, pressing either Ctrl-C or Ctrl-Z (latter followed by Enter) will abnormally terminate the program with one of those exceptions respectively. The handlers ensure that the program terminates without crashing and without giving a stack trace.