使用一个空的“除外”有什么错吗?

我尝试使用 PyAutogui 创建一个函数来检查屏幕上是否显示了一个图像,结果得出如下结论:

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

它运行良好,但 PyCharm 告诉我,我不应该离开 except赤裸。这样放着有什么问题吗?是否有更合适的方法来创建相同的函数?

75843 次浏览

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

Basically, you're not taking advantage of the language to help you find problems. If you used except Exception as ex: you could do something like log the exception and know exactly what happened.