[Python-Dev] PEP 463: Exception-catching expressions

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Feb 22 01:15:13 CET 2014

Eli Bendersky wrote:
> For instance, it is sometime non-trivial to know which exceptions some 
> function may throw. When you write a try...raise statement, you think 
> hard about covering all the bases. In an expression you're unlikely to,

Speak for yourself. I don't think I would put any less
thought into which exception I caught with an except
expression as I would for an except statement.

In fact, an except expression may even make it easier
to catch exceptions in an appropriately targeted way.
For example, a pattern frequently encountered is:

    result = computation(int(arg))

and you want to guard against arg not being a
well-formed int. It's tempting to do this:

       result = computation(int(arg))
    except ValueError:
       abort("Invalid int")

But that's bad, because the try clause encompasses
too much. Doing it properly requires splitting up the

       i = int(arg)
       abort("Invalid int")
       result = computation(i)

With an except expression, it could be written:

    result = computation(int(arg)
       except ValueError: abort("Invalid int"))


More information about the Python-Dev mailing list