擅长:python、mysql、java
<p>检查异常在Python中是不存在的。但是Python在异常类层次结构中确实有一些相似之处。以下是Java结构:</p>
<p><img src="https://i.stack.imgur.com/HngWy.png" alt=""/><a href="https://stackoverflow.com/questions/37170572/why-do-you-need-to-catch-exception-but-not-the-subclass-runtimeexception">source</a></p>
<p>在Java中,如果方法将抛出<code>Exception</code>或任何继承自<code>Exception</code>的类,而不是<code>RuntimeException</code>,则必须在方法签名中声明。此规则称为已检查异常。。它迫使用户考虑它们或应用程序将不编译。<p>
<p>在Python中,我们仍然有一个类似的概念,但没有强制执行。您可能听说过,使用bare-except语句是不好的风格,至少您应该选择捕获<code>Exception</code></p>
<pre><code>try:
foo()
except: # bad!
bar()
try:
foo()
except Exception: # somewhat better!
bar()
</code></pre>
<p>这是因为在Python中<code>Exception</code>从<code>BaseException</code>扩展而来,而一个裸的<code>except</code>将捕获所有内容。例如,您可能不想捕获引起<code>KeyboardInterrupt</code>的<code>ctrl+c</code>。如果你做一个空的<code>except:</code>,那么<code>KeyboardInterrupt</code>会被捕获,但是如果你做一个<code>except Exception:</code>,你会让这个气泡冒出来并停止应用程序。这是因为<code>KeyboardInterrupt</code>扩展了<code>BaseException</code>而不是<code>Exception</code>,因此不会被捕获</p>