自定义异常中的默认消息 – Python

我想在
Python中创建一个自定义异常,当没有任何参数引发时,它将打印一个默认消息.

案例:

>>> class CustomException(Exception):
       # some code here

>>> raise CustomException

并获得以下输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!

最佳答案 解决方案由以下代码给出:

class CustomException(Exception):
    def __init__(self, *args, **kwargs):
        default_message = 'This is a default message!'

        # if any arguments are passed...
        if args or kwargs:
            # ... pass them to the super constructor
            super().__init__(*args, **kwargs)
        else: # else, the exception was raised without arguments ...
                 # ... pass the default message to the super constructor
                 super().__init__(default_message)

一个等效但更简洁的解决方案是:

class CustomException(Exception):
     def __init__(self, *args, **kwargs):
         default_message = 'This is a default message!'

         # if no arguments are passed set the first positional argument
         # to be the default message. To do that, we have to replace the
         # 'args' tuple with another one, that will only contain the message.
         # (we cannot do an assignment since tuples are immutable)
         if not (args or kwargs): args = (default_message,)

         # Call super constructor
         super().__init__(*args, **kwargs)

一个更简洁但受限制的解决方案,只能在不带参数的情况下引发CustomException:

class CustomException(Exception):
     def __init__(self):
         default_message = 'This is a default message!'
         super().__init__(default_message)

如果您只是将字符串文字传递给构造函数而不是使用default_message变量,您当然可以在上述每个解决方案中保存一行.

如果您希望代码与Python 2.7兼容,那么您只需将super()替换为super(CustomException,self).

现在运行:

>>> raise CustomException

将输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.CustomException: This is a default message!

和运行:

raise CustomException('This is a custom message!')

将输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.CustomException: This is a custom message!

这是前两个解决方案代码将产生的输出.最后一个解决方案的不同之处在于,使用至少一个参数调用它,例如:

raise CustomException('This is a custom message!')

它将输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given

因为它不允许任何参数在引发时传递给CustomException.

点赞