[Tutor] using exceptions to implement case/switch?

Bill Campbell bill at celestial.net
Fri Oct 15 18:56:06 CEST 2004


I'm looking for feedback on the pros and cons of using exceptions to
implement constructions similar to the C switch or other language's case
statements.

I'm in the process of converting bunch of C code that makes extensive use
of switch() statements.  In particular I'm doing a python curses
implementation where it's parsing keys as they are pressed with different
case parts when special keys are hit.  Rather than doing this with a set of
``if'' statements, this could be done using exceptions, perhaps as in the
code below.

# start
import curses
import curses.ascii as ascii

keyf1 = 'key F1 pressed'
keyf2 = 'key F2 pressed'
keyf3 = 'key F3 pressed'
keyf4 = 'key F4 pressed'
# ...

def getchar(win):
	'''Get printable character from curses window'''
	while True:
		c = win.getch()
		if ascii.isprint(c) : return c
		if c == curses.KEY_F1 : raise keyf1
		if c == curses.KEY_F2 : raise keyf2
		if c == curses.KEY_F3 : raise keyf3
		if c == curses.KEY_F4 : raise keyf4
		curses.beep()

win = something_to_initialize_curses_window()

while True:
	try:
		c = getchar(win)
	except keyf1:
		process_keyF1()
	except (keyf2, keyf3):
		process_keyf2andf3()
	except keyf4:
		process keyf4()
	# ...
#end...

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``I have no reason to suppose that he, who would take away my Liberty, would
not when he had me in his Power, take away everything else.''  John Locke


More information about the Tutor mailing list