Bare

编程入门 行业动态 更新时间:2024-10-22 12:35:09
本文介绍了Bare-Except's 不受欢迎的任何原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以一种有限的方式,我想知道为什么在 Python 中使用裸机除外如此不受欢迎.

如果我有一个完整的程序在运行并且我执行以下操作,我就会明白:

导入系统从应用程序导入程序尝试:程序.开始()除了:打印 >>sys.stderr, "它没有用"

我正在压制重要信息并且没有得到真正的输出.但是让我们考虑一下我正在为配置设置执行 IO 操作,如果配置不存在或损坏,我有一组模板数据可以使用:

导入操作系统从配置导入 load_data从模板导入 save_datadir = os.path.expanduser('~')path = os.path.join(dir, 'config.txt')尝试:加载数据(路径)除了:保存数据(路径)

我想在这种情况下,是否最好构建一个捕获操作的自定义异常,以便为阅读代码的人提供更多信息?

解决方案

你的例子是一个精彩的例子,说明为什么这是一个坏主意.您的程序不是如果数据不存在或损坏,请用模板覆盖它".您的程序是如果出现任何问题,请尝试用模板覆盖数据".

例如,如果您在尝试加载数据时执行的代码中有拼写错误,您的程序将不会通知您,而是使用模板覆盖您的所有(有效!)数据.这可能是一个相当灾难性的错误,无论是在丢失数据方面,还是在您的测试用例遗漏的不经常使用的代码路径中发生拼写错误时,您都可以轻松地说服自己这不可能是问题.

另一个出错的例子是,如果用户决定尝试使用 Ctrl+C 中止程序.您会发现 KeyboardInterrupt 并立即破坏他的所有数据.

In a limited fashion, I'm wondering why it's so frowned upon to use a bare-except in Python.

I get that if I have a full program running and I do something like:

import sys from application import program try: program.start() except: print >> sys.stderr, "It didn't work"

I'm suppressing vital information and getting no real output. But let's consider I'm doing an IO operation for configuration settings, and I have a template set of data to use if the configuration is non-existent or corrupt:

import os from config import load_data from template import save_data dir = os.path.expanduser('~') path = os.path.join(dir, 'config.txt') try: load_data(path) except: save_data(path)

I guess in this case, is it better to build in a custom exception that catches the operation so it provides more information to someone reading the code?

解决方案

Your example is a wonderful example of why this is a bad idea. Your program is not "if the data is nonexistent or corrupt, overwrite it with a template". Your program is "if anything at all goes wrong, try to overwrite the data with a template".

For example, if you had a typo in the code that gets executed while trying to load the data, your program will not inform you, and instead overwrite all of your (valid!) data with the template. This could be a rather disastrous bug, both in terms of lost data, and how easily you can convince yourself that this couldn't possibly be the problem, should the typo occur in an infrequently exercised code path that your test cases miss.

Another example of things going wrong is if the user decided to try and abort the program with Ctrl+C. You'd catch the KeyboardInterrupt and promptly clobber all of his data.

更多推荐

Bare

本文发布于:2023-11-25 15:37:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Bare

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!