[Tutor] (no subject)

Dave Angel d at davea.name
Wed Jun 20 03:04:59 CEST 2012


On 06/19/2012 06:48 PM, Mark Lawrence wrote:
> On 19/06/2012 21:07, Dave Angel wrote:
>> On 06/19/2012 03:35 PM, Selby Rowley-Cannon wrote:
>>> Mailing list;
>>>          I have a small, [for the most part] functioning translation
>>> app for Rydish, a language created for the sole purpose of an RPG.
>>> The only problem is when I enter a word that has not yet been
>>> translated, I get this error:
>>>
>>> Traceback (most recent call last):
>>>    File "translator.py", line 25, in<module>
>>>      Etranslate()
>>>    File "translator.py", line 14, in Etranslate
>>>      print(Edictionary[Eword])
>>> KeyError: 'world'
>>>
>>> Is there a way to print a user-freindly message instead of
>>> displaying a traceback?
>>> Thanks,
>>>          -Selby
>>>
>>>
>>
>> Even easier than catching an exception is to test for the condition you
>> expect might not pass.  Assuming your Edictionary is a dict, all you
>> need to do is to make the reference conditional on the presence of that
>> particular key.
>>
>> if Eword in Edictionary:
>>      print(Edictionary[Eword])
>> else:
>>      print("oops....
>>
>>
>>
>
> But note the comparison between LBYL and EAFP - I'll leave those
> interested to google for it :)
>

If the program is multithreaded, or if it's NOT a dictionary, then
perhaps LBYL is not the right answer.  Otherwise, it describes what's
wanted, and doesn't risk catching too broad an exception.  I've seen far
too many programs that used a bare except to mask not only the
condition, but lots of other things.



-- 

DaveA



More information about the Tutor mailing list