美文网首页快乐学python
Python中BaseException和Exception的区

Python中BaseException和Exception的区

作者: DS事务所 | 来源:发表于2019-06-21 14:41 被阅读0次

分析源码发现 BaseException 是 Exception 的父类,作为子类的Exception无法截获父类BaseException类型的错误

class BaseError(BaseException):
    pass


try:
    raise BaseError
except:  # "except:" 是 "except BaseException:" 的省略写法
    print('BaseError 被 except: 捕获成功')

try:
    raise BaseError
except BaseException:
    print('BaseError 被 except BaseException: 捕获成功')

try:
    raise BaseError
except Exception:
    print(''BaseError 被 except Exception: 捕获成功')  # 此处不会打印因为捕获失败了
print('结束')
class Error(Exception):
    pass


try:
    raise Error
except Exception:
    print('Error 被 Exception 捕获成功')
print('结束')

相关文章

网友评论

    本文标题:Python中BaseException和Exception的区

    本文链接:https://www.haomeiwen.com/subject/glvyqctx.html