使用裸的“除外"有什么问题? [英] What is wrong with using a bare 'except'?

查看:15
本文介绍了使用裸的“除外"有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 PyAutoGui 制作一个函数来检查图像是否显示在屏幕上并想出了这个:

I tried making a function to check if an image is displayed on the screen using PyAutoGui and came up with this:

def check_image_on_screen(image):
    try:
        pyautogui.locateCenterOnScreen(image)
        return True
    except:
        return False

而且它工作正常,但 PyCharm 告诉我我不应该让 except 空着.这样留下有什么问题?有没有更合适的方法来创建相同的函数?

And it works fine, but PyCharm tells me I shouldn't leave except bare. What is the problem with leaving it like this? Is there a more appropriate way of creating the same function?

推荐答案

Bare except 将捕获您几乎肯定不想捕获的异常,包括 KeyboardInterrupt(用户按 Ctrl+C) 和 Python 引发的错误,如 SystemExit

Bare except will catch exceptions you almost certainly don't want to catch, including KeyboardInterrupt (the user hitting Ctrl+C) and Python-raised errors like SystemExit

如果您没有预期的特定异常,至少 except Exception,这是所有常规"异常的基本类型.

If you don't have a specific exception you're expecting, at least except Exception, which is the base type for all "Regular" exceptions.

话虽如此:您使用 except 块从已知的故障状态中恢复.未知的失败状态通常是不可恢复的,在这些状态下致命地退出是正确的行为,这是 Python 解释器在遇到未捕获的异常时自然会做的事情.

That being said: you use except blocks to recover from known failure states. An unknown failure state is usually irrecoverable, and it is proper behavior to fatally exit in those states, which is what the Python interpreter does naturally with an uncaught exception.

捕获您知道如何处理的所有内容,然后让其余部分向上传播调用堆栈,看看是否有其他东西可以处理它.在这种情况下,您期望的错误(根据 the docs)是 pyautogui.ImageNotFoundException

Catch everything you know how to handle, and let the rest propagate up the call stack to see if something else can handle it. In this case the error you're expecting (per the docs) is pyautogui.ImageNotFoundException

这篇关于使用裸的“除外"有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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