What is wrong with using a bare 'except'? [duplicate]

▼魔方 西西 提交于 2019-12-19 12:31:11

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!