在 Python 中捕获所有异常的坏主意 [英] Bad idea to catch all exceptions in Python

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

问题描述

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

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

我知道使用 except: 子句捕获所有异常甚至会捕获特殊"python 异常:SystemExitKeyboardInterruptGeneratorExit.那么为什么不直接使用 except Exception: 子句来捕获所有异常?

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.

因此,应大众要求,这是一个示例.一位程序员正在编写 Python 代码,她收到了 IOError.她没有进一步调查,而是决定捕获所有异常:

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

她没有以他的方式意识到这个问题:如果文件存在并且可以访问,但它是空的怎么办?然后此代码将引发 IndexError(因为列表 lines 为空).所以她会花几个小时想知道为什么当文件存在并且没有被锁定时她会从这个函数中返回 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天全站免登陆