如何知道Python是内置的还是用户定义的异常

时间:2019-03-20 14:01:29

标签: python exception

我有自己的异常类,它继承自Exception类。我可以检查type是否为in {..my exceptions list..},但就我而言,这似乎有问题。还有其他方法可以检查异常是用户定义的还是Python的内置异常。谢谢!

编辑:问题是其他人可以在其文件中编写自己的异常或重命名现有异常,而我可能无法跟踪这些异常。我需要记录内置异常,并忽略由于用户的错误而引发的异常。我需要除区块以外的地方签入

try:
    # something
except Exception as god_knows_what_ex:
    # check if built-in

4 个答案:

答案 0 :(得分:2)

您可以创建自己的自定义异常类,该类继承自Exception,并让您当前的异常类继承自该类。

所以基本上:

Exception
 - MyExceptionClass
    - MyExceptionClass1
    - MyExceptionClass2
 - Built-in exceptions

这样,您可以检查异常是否是MyExceptionClass的实例。

然后,如果您只想知道抛出的异常是用户定义的,则可以执行以下操作:

try:
    method_that_can_throw_an_exception()
except MyExceptionClass:
    print('User-defined exception thrown')

答案 1 :(得分:1)

我怀疑这个问题是由于您的代码具有以下反模式:

try:
    # bad code
except Exception as e:
    # catch all exceptions in the world, and try to
    # understand the type of e in superfluous ways

您不应(通常)检查异常的type,而应将except与相关异常类型的最小子集一起使用:


try:
    # bad code
except (CustomException1, CustomException2):
    # handle exception

或者,如果每种异常类型都需要不同的处理方式:

try:
    # bad code
except CustomException1:
    # handle CustomException1
except CustomException2:
    # handle CustomException2

答案 2 :(得分:1)

针对这种情况的一个好的设计是为您的类定义一个基本异常。如果有人想扩展您的模块,请在您的文档中明确指出他们必须使用您的异常类型或对其进行扩展。使用基类创建UserException。在记录代码中,忽略UserException并记录其他所有内容。

记录此行为。

您的方法可能行不通。您可以从以下开始:

ex.__class__.__module__

对于预定义的异常,它将返回__builtin__,但对于标准Python模块(库中的* .py文件)中定义的异常,则不会返回。

此外,您打算如何支持代码的用户使用pip安装的其他模块定义的异常?

答案 3 :(得分:0)

尽管这个问题的原因值得怀疑,但是这里有一个替代方案:

code.py

#!/usr/bin/env python3

import sys
import json


class UserError:
    pass


class UserException(BaseException):
    pass


def builtin_exc(exc_inst):
    return getattr(getattr(exc_inst, "__class__", None), "__module__", None) == "builtins"


def main():
    user_err = UserError()
    user_exc = UserException()
    base_exc = BaseException()
    exc = Exception()
    ni_err = NotImplementedError()
    jsdec_err = json.JSONDecodeError("", "", 0)
    for item in [user_err, user_exc, base_exc, exc, ni_err, jsdec_err]:
        print("'{:s}' is builtin: {:}".format(item.__class__.__name__, builtin_exc(item)))


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055262562]> "e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32

'UserError' is builtin: False
'UserException' is builtin: False
'BaseException' is builtin: True
'Exception' is builtin: True
'NotImplementedError' is builtin: True
'JSONDecodeError' is builtin: False