[Tutor] ValueError

Kushal Kumaran kushal.kumaran+python at gmail.com
Wed May 4 06:40:43 CEST 2011


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.

-- 
regards,
kushal


More information about the Tutor mailing list