0

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)

Community
  • 1
  • 1
bluedog
  • 935
  • 1
  • 8
  • 24
  • 1
    I feel like it could be a duplicate of this: http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python – sashkello Nov 12 '13 at 00:24
  • You can subclass Exception class for your own types of exceptions, where you can add any additional information. – unixmin Nov 12 '13 at 01:05
  • @sashkello I don't think it's a duplicate of that question because that question just uses a string. I think the exception classes usually accept a string as part of their definition. I am asking about adding arbitrary extra data. – bluedog Nov 12 '13 at 01:18

2 Answers2

1

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

if temp < 0:
    raise RuntimeError(temp, "Wicked Cold")
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

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.

John Spong
  • 1,361
  • 7
  • 8