[Tutor] ValueError

Kushal Kumaran kushal.kumaran+python at gmail.com
Sat May 7 18:15:20 CEST 2011


On Wed, May 4, 2011 at 3:13 PM, Peter Otten <__peter__ at web.de> wrote:
> Kushal Kumaran wrote:
>
>> On Tue, May 3, 2011 at 5:31 PM, Peter Otten <__peter__ at web.de> wrote:
>>> <snip>
>>>
>>> Also you should make the try...except as narrow as possible
>>>
>>> try:
>>> centimeters = float(centimeters)
>>> except ValueError as e:
>>> print e
>>>
>>> is likely to catch the float conversion while with many statements in the
>>> try-suite you are more likely to hide a problem that is unrelated to that
>>> conversion.
>>>
>>
>> I would have expected it to be the other way.  If you cannot
>> reasonable expect to continue after an exception, then the try block
>> should extend all the way across the block of code you want to skip.
>> In your snippet, what if some code later is relying on the
>> 'centimeters' variable having a useful float value?  IMO,
>> encapsulating small bits of code in try ... except blocks really makes
>> code written using exceptions look ugly.
>
> Instead of repeating what Alan said I'll give you a side-by-side example:
>
> <snip code>

Thanks Peter.  That was an interesting example.

-- 
regards,
kushal


More information about the Tutor mailing list