错误的想法来捕获Python中的所有异常 [英] Bad idea to catch all exceptions in Python

查看:135
本文介绍了错误的想法来捕获Python中的所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Python中捕获所有异常是一个坏主意?



我明白,使用捕获所有异常,除了:子句甚至会捕获'特殊'的python异常: SystemExit KeyboardInterrupt GeneratorExit 。那么为什么不用一个除了Exception:子句来捕获所有异常?

解决方案

因为它是非常非特定的,它不能让你做任何有趣的例外。此外,如果您捕获每个异常,可能会出现一些您甚至不知道发生的异常异常(这可能会导致您的应用失败,而您真的不知道为什么)。您应该能够预测(通过阅读文档或实验)具体要处理哪些异常以及如何处理它们,但是如果您从头开始盲目地抑制所有这些异常,您将永远不会知道。



所以,受欢迎的请求,这里是一个例子。程序员正在编写Python代码,并获得一个 IOError 。而不是进一步调查,她决定捕获所有例外:

  def foo():
try:
f = open(file.txt)
lines = f.readlines()
返回行[0]
除了:
返回无

她没有意识到这个问题:如果文件存在且可以访问,但是是空的?那么这个代码将引发一个 IndexError (因为列表是空的)。所以她会花几个小时想知道为什么她在文件存在的时候从这个函数中获得捕获错误,这是她正在访问可能不存在的数据。


Why is it a bad idea to catch all exceptions in Python ?

I understand that catching all exceptions using the except: clause will even catch the 'special' python exceptions: SystemExit, KeyboardInterrupt, and GeneratorExit. So why not just use a except Exception: clause to catch all exceptions?

解决方案

Because it's terribly nonspecific and it doesn't enable you to do anything interesting with the exception. Moreover, if you're catching every exception there could be loads of exceptions that are happening that you don't even know are happening (which could cause your application to fail without you really knowing why). You should be able to predict (either through reading documentation or experimentation) specifically which exceptions you need to handle and how to handle them, but if you're blindly suppressing all of them from the beginning you'll never know.

So, by popular request, here's an example. A programmer is writing Python code and she gets an IOError. Instead of investigating further, she decides to catch all exceptions:

def foo():
    try:
        f = open("file.txt")
        lines = f.readlines()
        return lines[0]
    except:
        return None

She doesn't realize the issue in his ways: what if the file exists and is accessible, but it is empty? Then this code will raise an IndexError (since the list lines is empty). So she'll spend hours wondering why she's getting None back from this function when the file exists and isn't locked without realizing something that would be obvious if she had been more specific in catching errors, which is that she's accessing data that might not exist.

这篇关于错误的想法来捕获Python中的所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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