[Tutor] Re: Exceptions

Brian van den Broek bvande at po-box.mcgill.ca
Mon Apr 18 03:44:42 CEST 2005


Diana Hawksworth said unto the world upon 2005-04-17 20:05:
> Brian - thanks for your continuing help!  Here is ALL of the code.  Sure
> hope you can help. Cheers. Diana

Hi Diana,

whew! A bit of an adventure, but I think I've got it. (The adventure 
comes in as I have used Tkinter about twice. I've done almost no GUI 
programming; most of it has been in playing with the Pythoncard 
tutorials and demos. :-)

I've snipped away all but the relevant code.

>     def reveal(self):
>         """ Display message based on number. Changing text widget to integer
>             Correcting the entry of a string variable - except the error
> checking isn't working!"""
> 
>         try:
>             self.guess = int(self.num_ent.get())
> 
>         except(ValueError),e:
	
Here, I put in a line:

	      print "I'm in the except block!"  # XXX

This made the message print in the interactive window. (I ran this 
through PythonWin, so had the PythonWin interactive window visible 
underneath your app.) That confirms that the exception is being raised 
and caught as desired. So, it must be that there is something faulty 
in how you are constructing the message.

For future reference, a few print statements sprinkled about are worth 
a lot of debugging time! I like to append mine with # XXX so I can 
quickly find them when it comes time to extract them.

A false start later, I worked it out as below.

>             message = "%s is not a number. Please try again!" %self.guess
> 
>         else:
>             self.num_ent.delete(0,END)
>             self.num_ent.focus_set()
> 
>             if self.guess < self.number:
>                 message = "%s is too low! You need to guess higher. "
> %self.guess
> 
>             if self.guess > self.number:
>                 message = "%s is too high! You need to guess lower."
> %self.guess
> 
>             if self.guess == self.number:
>                 message = "%s is the correct number!" %self.guess
> 
>                 self.message_txt.config(state = NORMAL)
>                 self.message_txt.config(state = DISABLED)

Here's the problem. I don't know the relevant lingo, but this is the 
chunk of code which makes the message display in your widget. *But* it 
is in your else clause in the try/except/else construct. So, if an 
exception is raised, it isn't run. Outdent it so that it is hit 
irrespective of the flow going through the except or the else, and all 
is golden!


>             self.message_txt.config(state = NORMAL)
>             self.message_txt.delete(0.0, END)
>             self.message_txt.insert(0.0, message)
>             self.message_txt.config(state = DISABLED)

HTH,

Brian vdB



More information about the Tutor mailing list