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)

3
  • 1
    I feel like it could be a duplicate of this: stackoverflow.com/questions/9157210/… Commented Nov 12, 2013 at 0:24
  • You can subclass Exception class for your own types of exceptions, where you can add any additional information. Commented Nov 12, 2013 at 1: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. Commented Nov 12, 2013 at 1:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.