[Tutor] Re: exceptions

Andrei project5 at redrival.net
Sat Apr 16 11:32:37 CEST 2005


Diana Hawksworth <dianahawks <at> optusnet.com.au> writes:

> I have been trying to trap a string entry by raising an exception.  The code
follows - but the exception is
> never raised.  What am I doing wrong?

I've snipped the code that is irrelevant to this question.

>  try:
>          self.guess = int(self.num_ent.get())
>  except(ValueError):
>          message = str(self.guess) + " is not a number. Please try again!"

Obviously it's hard to determine what's happening since I don't know that that
get() returns, nor what you do with the message. Now let's play with that a bit
in the interpreter:

>>> try:
...     guess = int('abc')
... except (ValueError):
...     print 'not a number'
not a number
>>> try:
...     guess = int('4')
... except (ValueError):
...     print 'not a number'
>>> try:
...     guess = int('abc')
... except (ValueError):
...     message = 'not a number'
>>> print message
not a number

The first run demonstrates that the code is working. The second run shows that
if your source doesn't return any invalid data, the exception will not be
raised. The third run shows that the exception is triggered, but you will simply
not notice it if you don't do anything with message. 

By the way, the third implementation contains a potential problem: if the
message variable does not exist before the try-except and everything goes well,
you'll get a NameError if you try to print it. Also if it does exist, it will
need to be reset before the try-except, otherwise afterwards you won't know
whether its value comes from the last try-except or from some time in the past.

On a sidenote: recommended Python style is to use 4 spaces per indentation level.

Yours,

Andrei



More information about the Tutor mailing list