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

2014年2月21日 16:18:07 -0800

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:
 try:
 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
expression:
 try:
 i = int(arg)
 except:
 abort("Invalid int")
 else:
 result = computation(i)
With an except expression, it could be written:
 result = computation(int(arg)
 except ValueError: abort("Invalid int"))
--
Greg
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to