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

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

问题描述

我尝试使用PyAutoGui尝试检查屏幕上是否显示了图像,并提出了以下解决方案:

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

它工作正常,但是PyCharm告诉我我不应该裸露except.留下这样的问题是什么?有没有更合适的方法来创建相同的功能?

解决方案

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

这样的错误

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


就是说:您使用except块从已知的故障状态中恢复.未知的失败状态通常是无法恢复的,在这些状态下致命退出是适当的行为,这是Python解释器自然而然地发生的未捕获异常.

捕获所有您知道如何处理的内容,然后让其余的内容传播到调用堆栈中,以查看是否有其他内容可以处理它.在这种情况下,您预期的错误(每个文档)为pyautogui.ImageNotFoundException

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

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 will catch exceptions you almost certainly don't want to catch, including KeyboardInterrupt (the user hitting Ctrl+C) and Python-raised errors like SystemExit

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


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.

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