我应该总是在 `except` 语句中指定异常类型吗? [英] Should I always specify an exception type in `except` statements?

查看:34
本文介绍了我应该总是在 `except` 语句中指定异常类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 PyCharm IDE 时,使用 except: 没有异常类型会触发来自 IDE 的提醒,该异常子句是太宽泛.

When using PyCharm IDE the use of except: without an exception type triggers a reminder from the IDE that this exception clause is Too broad.

我应该忽略这个建议吗?或者总是指定异常类型是 Pythonic 吗?

Should I be ignoring this advice? Or is it Pythonic to always specific the exception type?

推荐答案

指定显式异常类型几乎总是更好.如果您使用裸 except: 子句,您最终可能会捕捉到您希望捕捉到的异常之外的异常 - 这可能会隐藏错误或使程序在不执行您的操作时更难调试期待.

It's almost always better to specify an explicit exception type. If you use a naked except: clause, you might end up catching exceptions other than the ones you expect to catch - this can hide bugs or make it harder to debug programs when they aren't doing what you expect.

例如,如果您要向数据库中插入一行,您可能希望捕获指示该行已存在的异常,以便您可以进行更新.

For example, if you're inserting a row into a database, you might want to catch an exception that indicates that the row already exists, so you can do an update.

try:
    insert(connection, data)
except:
    update(connection, data)

如果你指定一个空的except:,你还会发现一个套接字错误,表明数据库服务器已经倒下.最好只捕获您知道如何处理的异常 - 程序在异常点失败通常比继续执行但以奇怪的意外方式运行要好.

If you specify a bare except:, you would also catch a socket error indicating that the database server has fallen over. It's best to only catch exceptions that you know how to handle - it's often better for the program to fail at the point of the exception than to continue but behave in weird unexpected ways.

您可能想要使用裸 except: 的一种情况是在您需要始终运行的程序的顶层,例如网络服务器.但是,您需要非常小心地记录异常,否则将无法弄清楚出了什么问题.基本上,程序中最多只能有一个地方这样做.

One case where you might want to use a bare except: is at the top-level of a program you need to always be running, like a network server. But then, you need to be very careful to log the exceptions, otherwise it'll be impossible to work out what's going wrong. Basically, there should only be at most one place in a program that does this.

所有这一切的一个推论是你的代码永远不应该raise Exception('some message'),因为它强制客户端代码使用except:(或except Exception: 这是几乎一样糟糕).您应该定义一个特定于您想要发出信号的问题的异常(可能继承自某些内置异常子类,例如 ValueErrorTypeError).或者您应该引发特定的内置异常.这使您的代码用户能够小心地捕获他们想要处理的异常.

A corollary to all of this is that your code should never do raise Exception('some message') because it forces client code to use except: (or except Exception: which is almost as bad). You should define an exception specific to the problem you want to signal (maybe inheriting from some built-in exception subclass like ValueError or TypeError). Or you should raise a specific built-in exception. This enables users of your code to be careful in catching just the exceptions they want to handle.

这篇关于我应该总是在 `except` 语句中指定异常类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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