问题描述
说,鼓励程序员从Exception类或其子类之一而不是BaseException派生新的异常。
The Python 2 documentation says that "programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException". Without any further explanation as to why.
我很好奇为什么建议采用这种方式?仅仅是为了保留,因为Python开发人员已经设想到了它?
I am curious as to why it is recommended this way? Is it just to preserve the exceptions hierarchy as Python developers envisioned it?
>>> dir(BaseException) == dir(Exception)
True
推荐答案
从 BaseException
派生的异常是: GeneratorExit
, KeyboardInterrupt
, SystemExit
。
Exceptions derived from BaseException
are: GeneratorExit
, KeyboardInterrupt
, SystemExit
.
根据文档:
- :在调用生成器的close()方法时引发。它直接从BaseException继承,而不是从StandardError继承,因为从技术上讲它不是错误。
- :当用户按下中断键(通常为Control-C或Delete)时引发。在执行期间,会定期检查中断。当内置函数input()或raw_input()等待输入时键入的中断也会引发此异常。 该异常继承自BaseException,以免被捕获Exception的代码意外捕获,从而防止解释器退出。
- :该异常继承自BaseException而不是StandardError或Exception这样它就不会被捕获Exception的代码意外捕获。 这允许异常正确传播并导致解释器退出。
GeneratorExit
: Raised when a generator‘s close() method is called. It directly inherits from BaseException instead of StandardError since it is technically not an error.KeyboardInterrupt
: Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function input() or raw_input() is waiting for input also raise this exception. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.SystemExit
: The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit.
所以通常的原因是防止 try ...,除了例外
意外阻止解释器退出( GeneratorExit
除外)
So the usual reasons are to prevent try ... except Exception
accidently prevent interpreter exit (except GeneratorExit
)
更新:
解释了原因。
except (KeyboardInterrupt, SystemExit):
raise
except:
...
这是不必要的。该PEP建议将
KeyboardInterrupt和SystemExit移至直接从
BaseException继承。
That is needlessly explicit. This PEP proposes moving KeyboardInterrupt and SystemExit to inherit directly from BaseException.
这篇关于为什么建议在Python中从Exception而不是BaseException类派生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!