Let me elaborate on the mildly cryptic question title.
In Python 3 we've got neat exception chaining feature, that lets you add more context to exceptions in the process of their propagation.
Recently, I wanted to attach extra exception information to the exception, but without throwing it straightaway. The code was doing some defensive processing in generator, so I wanted to yield it instead, so I tried something like:
def gen():
for row in csv_file:
try:
yield parse(row)
except Exception as e:
yield RuntimeError(f"Bad row: {row}") from e
To my disappointment, that didn't work! Turned out that raise EXCEPTION from CAUSE
is a compound operator as PEP-3134 explains.
To get around this in my code, I set __cause__ = e
manually and carried on. However, it still bothered me why it was implemented that way.
Imagine instead we had an operator from
with the following syntax: EXCEPTION from CAUSE
, doing exactly what raise .. from ..
is doing, except throwing, and returning new Exception
instead. That way:
- it's compatible, you can still use
raise .. from ..
syntax (now internally it'd be parsed asraise (.. from ..)
) - it would make everything more composable, allowing to attach cause without necessarily throwing (in particular my usecase). I can that it's a bit unusual use of exceptions though.
- presumably, that would also make implementation simpler, since you'd not need to modify and clash exiting primitive (simple
raise
operator). I see it as a main argument for my 'alternative form' of the operator from the perspective of Python language developer.
I've gone through PEP/googled but hasn't really found any rationale. I experimented to check if there is something else apart from __cause__
being set, but it doesn't seem so. I'm attaching bits of code that I used to check that:
def failing():
raise RuntimeError("function failed!")
def cause_from():
try:
failing()
except Exception as e:
raise RuntimeError("extra info") from e
def cause_manual():
try:
failing()
except Exception as e:
ee = RuntimeError("extra info")
ee.__cause__ = e
raise ee
It results in the same traceback:
$ python3 -c 'import exc; exc.cause_from()'
Traceback (most recent call last):
File "/tmp/exc.py", line 7, in cause_from
failing()
File "/tmp/exc.py", line 2, in failing
raise RuntimeError("function failed!")
RuntimeError: function failed!
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/exc.py", line 9, in cause_from
raise RuntimeError("extra info") from e
RuntimeError: extra info
$ python3 -c 'import exc; exc.cause_manual()'
Traceback (most recent call last):
File "/tmp/exc.py", line 13, in cause_manual
failing()
File "/tmp/exc.py", line 2, in failing
raise RuntimeError("function failed!")
RuntimeError: function failed!
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/exc.py", line 17, in cause_manual
raise ee
RuntimeError: extra info
The only difference in traceback is the line where exception was thrown (raise RuntimeError("extra info") from e
vs raise ee
). The cause_from
version looks somewhat more readable.
So it's the only reason I see for that choice of syntax structure, I wonder if it's also the intended motivation? Is it possible that I miss some subtle effect of raise .. from ..
as a compound operator?
mypy
(as opposed to checkingif future.is_error()
). – karlicoss Oct 12 at 15:43isinstance(something, Exception)
. It is not the right way of handling exceptions. They must be caught inexcept
clause. To do it you have toraise
them first. – sanyash Oct 12 at 16:01