Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

except

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?

like image 436
CaioRamaglio Avatar asked Mar 01 '19 16:03

CaioRamaglio


People also ask

What can I use instead of bare except?

When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

Why would using except exception be unhelpful?

Another disadvantage of passing and catching Exception (or bare except ) is that we will never know the second error when there are two errors in the code. The first error will always be caught first and we will get out of the try block.

What is except exception as e?

In contrast, the except Exception as e statement is a statement that defines an argument to the except statement. e in the latter statement is utilized to create an instance of the given Exception in the code and makes all of the attributes of the given Exception object accessible to the user.

What does except pass do?

The except:pass construct essentially silences any and all exceptional conditions that come up while the code covered in the try: block is being run. What makes this bad practice is that it usually isn't what you really want.


1 Answers

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

like image 125
Adam Smith Avatar answered Oct 02 '22 08:10

Adam Smith