Comment

Comment by csense

I disagree with promoting try / catch. Exceptions like ValueError can really happen almost anywhere, so it is usually better to sanitize your inputs.

E.g. something like:

    try: 
        something = myfunc(d['x'])
    except ValueError:
        something = None
The programmer's intent is probably to only catch errors in the key lookup d['x'], but if there is some bug in the implementation of myfunc() or any of the functions called by myfunc() which causes a ValueError to unintentionally be raised, it will be caught by the except.

For dictionary lookups specifically, get() is usually preferable:

    something = d.get('x')
    if something is not None:
        something = myfunc(something)
Or if dictionary may potentially contain None values:

    if 'x' in d:
        something = myfunc(d['x'])
parent csense 12 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton