Steven D'Aprano <[email protected]> added the comment:
It seems to me that an explicit raise inside an except block should *not* chain
exceptions by default. The rationale for chaining exceptions is to detect bugs
in the exception handler:
try:
something
except SomeError:
y = 1/x # oops, what happens when x == 0?
but an explicit raise isn't a bug. If you want it to chain for some reason,
it's easy to do:
try:
something
except SomeError as exp:
raise MyException from exp
or otherwise set __content__, but there's no simple way to avoid chaining
except via boilerplate code.
I frequently use the EAFP idiom to detect error conditions, and chained
exceptions exposes details to the caller that are irrelevant implementation
details. Here's a common example:
def process(iterable):
try:
x = next(iterable)
except StopIteration:
raise ValueError("can't process empty iterable")
continue_processing()
The fact that ValueError was raised in response to a StopIteration is an
irrelevant implementation detail that shouldn't be, and wasn't in 2.x, exposed.
Another practical example is avoiding isinstance checks:
def func(x):
try:
x + 0
except (ValueError, TypeError):
raise MyException('x is not a number')
do_something_with(x)
I note that PEP 3134 explicitly listed the issue of *not* chaining exceptions
as an open issue. Now that chained exceptions are being seen in the wild, it
seems that the inability to easily suppress chaining *is* a real issue for some
users:
http://mail.python.org/pipermail/python-list/2010-October/1258583.html
http://mail.python.org/pipermail/python-list/2010-December/1261738.html
----------
nosy: +stevenjd
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue6210>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com