[Tutor] How to exit this loop in the interpreter

spawgi at gmail.com spawgi at gmail.com
Fri May 4 08:39:33 CEST 2012


Thanks Jerry!

By the way, I know I can change the way the loops works and bypass this
issue :)
I just wanted to mention this behavior which I thought interesting and
present some corner case (I have worked extensively in testing).
And I agree, probably I should not have used color. Bad on my part.

Cheers!!
Sumod

On Thu, May 3, 2012 at 7:48 PM, Jerry Hill <malaclypse2 at gmail.com> wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
http://spawgi.wordpress.com
We can do it and do it better.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120504/505832d3/attachment.html>


More information about the Tutor mailing list