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

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

问题描述

当使用PyCharm IDE时,不使用异常类型的除了之外,会触发IDE的提醒,即该异常子句太宽泛code>。

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?

推荐答案

几乎总是更好的指定一个显式的异常类型。如果您使用裸体,除了:子句,您可能会最终捕获除了预期捕获的异常之外的异常 - 这可能会隐藏错误或使其难以调试程序没有做你想要的。

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)

如果指定一个裸露的,除了:,您还会捕获一个套接字错误,指出数据库服务器已经崩溃了。最好只能捕捉到你知道如何处理的异常 - 程序在异常的时候比通常更好,而不是继续,而是以奇怪的意想不到的方式行事。

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.

一种情况,您可能需要使用裸露的,除了:是您需要始终运行的程序的顶层,如网络服务器。但是,然后,您需要非常小心地记录异常,否则将无法解决出现的问题。基本上,程序中最多只能有一个地方执行此操作。

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.

所有这一切的结论是,您的代码不应该执行提升异常('some message'),因为它强制客户端代码使用,除了:(或除了异常: / code>这是几乎不好)。您应该定义一个特定于您想要发出的问题的异常(可能继承自某些内置的异常子类,如 ValueError TypeError )。或者你应该提出一个特定的内置异常。这使得您的代码的用户在捕捉他们想要处理的异常时要小心。

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天全站免登陆