The “correct” way to define an exception in Python without PyLint complaining

前端 未结 3 1191
长发绾君心
长发绾君心 2021-02-12 01:43

I\'m trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning.

First, the simplest way:

class My         


        
相关标签:
3条回答
  • 2021-02-12 01:56

    Alright, I think I figured it out. This seems to keep PyLint happy:

    class MyException(Exception):
        def __init__(self, message):
            Exception.__init__(self, message)
            self.message = message
    
    0 讨论(0)
  • 2021-02-12 01:57

    When you call super, you need the subclass/derived class as the first argument, not the main/base class.

    From the Python online documentation:

    class C(B):
        def method(self, arg):
            super(C, self).method(arg)
    

    So your exception would be defined as follows:

    class MyException(Exception):
        def __init__(self, message):
            super(MyException, self).__init__(message)
            self.message = message
    
    0 讨论(0)
  • 2021-02-12 02:03

    Your first way should work. I use it myself all the time in Python 2.6.5. I don't use the "message" attribute, however; maybe that's why you're getting a runtime warning in the first example.

    The following code, for example, runs without any errors or runtime warnings:

    class MyException(Exception):
        pass
    
    def thrower():
        error_value = 3
        raise MyException("My message", error_value)
        return 4
    
    def catcher():
        try:
            print thrower()
        except MyException as (message, error_value):
            print message, "error value:", error_value
    

    The result:

    >>> catcher()
    My message error value: 3
    

    I don't know if PyLint would have a problem with the above.

    0 讨论(0)
提交回复
热议问题