【问题标题】:Defining custom exceptions in Python在 Python 中定义自定义异常
【发布时间】:2026-02-17 20:45:02
【问题描述】:

本题参考:

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

就干净的代码而言,定义异常的理想方法是这样的:

class MyException(Exception):
    pass

但是,如引用问题中所述,这会导致运行时警告:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

接受的答案似乎是定义消息方法:

class MyException(Exception):
    def __init__(self, message):
        super(MyException, self).__init__(message)
        self.message = message

除了 4 行更杂乱且可读性较差之外,最大的问题是您必须重复输入新异常的名称 (MyException) 两次。

我不经常在 Python 中使用类,所以如果我在这里偏离基础,请原谅我,但处理这个问题的更好方法是使用非贬值的 .message 方法定义您自己的基础异常因为 Python 似乎在使用来自BaseException 的那个时遇到了问题? ::

# Do this only once:
class MyBaseException(Exception):
    def __init__(self, message):
        super(MyBaseException, self).__init__(message)
        self.message = message

# Whenever you want to define a new exception:
class NewException(MyBaseException):
    pass

【问题讨论】:

  • 问题是什么?我只看到一个声明。你问对不对?
  • 我会选择简单的 2 班轮解决方案...
  • 你的问题不在于如何定义它(如果你不覆盖默认行为,你没有,那么不要覆盖__init__),但显然你如何使用它,因为当您 访问 属性时会引发警告。所以在那里修复它。

标签: python exception-handling


【解决方案1】:

您似乎在代码中的某处使用了 MyException.message 你可以改成

try: 
   <some code>
except MyException as msg:
    <handle>

【讨论】: