[Tutor] How to exit this loop in the interpreter
Jerry Hill
malaclypse2 at gmail.com
Thu May 3 16:18:11 CEST 2012
On Thu, May 3, 2012 at 9:57 AM, <spawgi at gmail.com> wrote:
> Hello all,
>
> I have encountered the following scenario.
> Here is the code - on IDLE on Windows XP.
>
>>>> while True:
> try:
> number = raw_input("enter number - ")
> print number * number
> except ValueError:
> print "invalid number"
> except:
> print "unspecified exception"
> else:
> print "other conditions"
>
>
> enter number - 3
> unspecified exception
>
> What I noticed is that no matter, what input I give, I cannot exit this
> loop. I have tried control-C, control-D etc. all the keys. So how can I exit
> from this loop?
You can't, because you've painted yourself into a corner. The bare
"except:" line will catch any exception at all. Including the
KeyboardInterrupt exception that is raised when you hit control-c. If
you must catch unknown exceptions, but still want to allow the
KeyboardInterrupt exception from pressing control-c to exit your
program, then use "except Exception:"
instead of a bare "except:" statement. Since KeyboardInterrupt (and
SystemExit) are not subclasses of Exception, they won't be caught.
KeyboardInterrupt and SystemExit are subclasses of a class called
BaseException, instead of Exception, for this exact purpose. See more
about python's exception hierarchy here:
http://docs.python.org/library/exceptions.html
--
Jerry
More information about the Tutor
mailing list