![](/img/trans.png)
[英]Why is it recommended to derive from Exception instead of BaseException class in Python?
[英]why should we use Exception as a superclass, why not BaseException
在python中,每当我们编写用户定义的异常时,我们都必须从类Exception
扩展它。 我的问题是为什么我们不能从BaseException
扩展它,它是异常层次结构的超类,而Exception
也是BaseException
子类。
BaseException
包括KeyboardInterrupt
和SystemExit
类的东西,它们使用异常机制,但是大多数人不应该抓住它。 如果您熟悉它,它类似于Java中的Throwable
。 直接从BaseException
派生的东西通常用于在执行finally
块和上下文管理器__exit__
方法时关闭系统以释放资源。
根据Python2文档 ,有四个例外是BaseException
衍生物:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
非Exception
的三个实际上并不是错误,这意味着通常你不想捕获它们就好像它们是错误一样。 在Python2.5中添加了BaseException
(在此之前,没有BaseException
,其他异常是从Exception
子类化的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.