bluedog
bluedog

Reputation: 955

Adding additional infomation to Python Exceptions

Python noob question that's not easy to Google. Coming from C++ I'm still coming to grips with what can be done in Python.

I want to raise an exception in Python and add a number and string value to the exception. The exception must be a standard Python exception, not a custom one. I was planning on using RuntimeError.

So, can I add a number and string value to RuntimeError?

(Edit: Why don't I just use a custom exception? I tried! See Python: Referring to an Exception Class Created with PyErr_NewException in an Extension Module)

Upvotes: 0

Views: 129

Answers (2)

John Spong
John Spong

Reputation: 1381

You can, and it will be stored in the args attribute

>>> try: 
...     raise RuntimeError('test', 5)
... except Exception as e:
...     print e.args
...
('test', 5)

I would think twice about your restriction against creating your own exception type; proper exception types are extremely important.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168616

The initializer for RuntimeError takes an arbitrary set of arguments. Like this:

if temp < 0:
    raise RuntimeError(temp, "Wicked Cold")

Upvotes: 1

Related Questions