Note that there are some explanatory texts on larger screens.

plurals
  1. POProper way to declare custom exceptions in modern Python?
    text
    copied!<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/" rel="noreferrer">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload