Dims
Dims

Reputation: 51209

How to raise additional error in Python and keep cause in stack trace?

I wrote

try:
    ...
except Exception as e:
    raise ValueError(e, "Was unable to extract date from filename '%s'" % filename)

and now, when exception occurs inside try block, I loose information about it. I stack trace printed I see only line number with raise statement and no infomation about where actual e occured.

How to fix?

Upvotes: 0

Views: 93

Answers (1)

Kos
Kos

Reputation: 72299

Use raise exc from another_exc:

try:
    ...
except Exception as e:
    raise ValueError("Was unable to extract date from filename '%s'" % filename) from e

Adding the from e will make sure there's two tracebacks connected by The above exception was the direct cause of the following exception".

Upvotes: 1

Related Questions