为什么我们应该使用Exception作为超类,为什么不是BaseException [英] why should we use Exception as a superclass, why not BaseException

查看:349
本文介绍了为什么我们应该使用Exception作为超类,为什么不是BaseException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,每当我们编写用户定义的异常时,我们必须从类 Exception 中扩展它。
我的问题是为什么我们不能从 BaseException 中扩展它,这是异常层次结构的超类,异常也是 BaseException 的子类。

In python, whenever we are writing User-defined exception, we have to extend it from class Exception. my question is why can't we extend it from BaseException which is super-class of exception hierarchy and Exception is also subclass of BaseException.

推荐答案

BaseException 包括使用异常机制的 KeyboardInterrupt SystemExit 大多数人不应该抓住。如果你熟悉的话,它类似于Java中的 Throwable 。直接从 BaseException 派生的东西通常旨在关闭系统,同时执行 finally 块和上下文管理器 __ exit __ 释放资源的方法。

BaseException includes things like KeyboardInterrupt and SystemExit, which use the exception mechanism, but which most people shouldn't be catching. It's analogous to Throwable in Java, if you're familiar with that. Things that derive directly from BaseException are generally intended to shut down the system while executing finally blocks and context manager __exit__ methods to release resources.

这篇关于为什么我们应该使用Exception作为超类,为什么不是BaseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆