Exception Messages

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Oct 15 20:47:17 EDT 2012


On Mon, 15 Oct 2012 09:00:15 -0700, Wanderer wrote:

> How do you get Exceptions to print messages? I have an exception defined
> like this
> 
> class PvCamError(Exception):
>     def __init__(self, msg):
>         self.msg = msg

Please don't invent yet another interface for exception messages. 
Exceptions already have two defined interfaces for accessing the error 
message:

exception.message  # older, now obsolete, and gone in Python 3.
exception.args  # recommended way

Please use the same interface that nearly all exceptions already have and 
use an "args" argument. The easiest way to do this is also the simplest:

class PvCamError(Exception): pass


If you *must* support "msg", do something like this:

class PvCamError(Exception):
    def __init__(self, msg, *args):
        super(PvCamError, self).__init__(msg, *args)  # see footnote [1]
        self.msg = msg





[1] If you're using Python 3, you can abbreviate the super call to:

    super().__init__(self, msg, *args)



-- 
Steven



More information about the Python-list mailing list