使用裸露的“除外"有什么问题?

编程入门 行业动态 更新时间:2024-10-27 20:32:05
本文介绍了使用裸露的“除外"有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试使用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

更多推荐

使用裸露的“除外"有什么问题?

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

发布评论

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

>www.elefans.com

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