Using a dict is first of all more efficient (look-up time of O(1) as opposed to the list.index's O(n)), and also reduces the need for try/except with the help of the get() method. The "problem" is that dicts' keys need to be hashable - which lists are not. So you will need to convert them to tuples (which are hashable):

buttons = {
    (PIN_5,): 1,
    (PIN_5, PIN_6): 2,
    (PIN_6,): 3,
    (PIN_6, PIN_19): 4
}

And now using the get method you check for a key, and if it is not found, it will return the second default argument:

button_pressed = buttons.get(tuple(pins_high), 0)

Note that this is "order-sensitive" - meaning that [PIN_6, PIN_5] will return 0 and not 2!

Answer from Tomerikoo on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself » · See more Error types in our Python Built-in Exceptions Reference.
🌐
W3Schools
w3schools.com › python › exercise.asp
Exercise: - Python Try Except
Pass3 q · Match3 q · While Loops5 q · For Loops5 q · Functions3 q · Args / Kwargs3 q · Args / Kwargs3 q · Decorators3 q · Scope3 q · Lambda4 q · Range3 q · Arrays3 q · Iterators3 q · Modules5 q · Dates4 q · Math4 q · JSON3 q · RegEx4 q · PIP3 q · Try Except3 q ·
🌐
W3Schools
w3schools.com › python › python_challenges_try_except.asp
Python Try...Except Code Challenge
Test your understanding of Python try...except by completing a small coding challenge.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions, for example: ... except RuntimeError, TypeError, NameError: ... pass
🌐
W3Schools
w3schools.com › python › ref_keyword_except.asp
Python except Keyword
The try keyword. The finally keyword. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
W3Schools
w3schools.com › python › python_if_pass.asp
Python Pass Statement
You need pass where Python expects a statement, not just a comment. ... You can use pass in any branch of an if-elif-else statement. ... value = 50 if value < 0: print("Negative value") elif value == 0: pass # Zero case - no action needed else: print("Positive value") Try it Yourself »
🌐
W3Schools
w3schoolsua.github.io › python › python_try_except_en.html
Python Try Except. Lessons for beginners. W3Schools in English
Python Try Except. Exception Handling. Many Exceptions. The else keyword. The finally block. Raise an exception. The raise keyword. Exercises. Examples. Lessons for beginners. W3Schools in English
Find elsewhere
🌐
W3Schools
w3schools.in › python › exception-handling
Python Exceptions Handling - W3Schools
As a programmer, if you don't want the default behavior, then code a 'try' statement to catch and recover the program from an exception. Python will jump to the 'try' handler when the program detects an error; the execution will be resumed. Event Notification: Exceptions are also used to signal ...
🌐
W3Schools
w3schools.com › python › gloss_python_try_else.asp
Python Try Else
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Try it Yourself » · Python Try Except Tutorial Error Handling Handle Many Exceptions Try Finally raise
🌐
W3Schools
w3schools.com › python › trypython.asp
Something went wrong The 'try except' is finished
Run ❯ Get your own Python server · ❯Run Code Ctrl+Alt+R Change Orientation Ctrl+Alt+O Change Theme Ctrl+Alt+D Go to Spaces Ctrl+Alt+P · Something went wrong The 'try except' is finished
🌐
DEV Community
dev.to › smac89 › better-way-to-tryexceptpass-in-python-2460
Better way to try...except...pass in Python - DEV Community
June 23, 2022 - The exception will never be visible outside of the context, therefore if you are being a good log keeper and in the habit of using logger.exception("I tried to do something"), the exception will not be shown by the logger. If you are already using this pattern, then I'm assuming you know what you're doing. The disadvantage mentioned might be a blocker for some. Consult your nearest python guru if you experience any adverse effects.
🌐
W3Schools
w3schools.com › python › trypython.asp
W3Schools online PYTHON editor
The W3Schools online code editor allows you to edit code and view the result in your browser
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - Using try … except with pass allows the program to ignore the exception and continue execution without taking any specific action in response to the error. However, this practice can hide potential issues, making it harder to debug and maintain ...
🌐
W3Schools
w3schools.com › python › ref_keyword_try.asp
Python try Keyword
try: x > 3 except: Exception("Something went wrong") Try it Yourself » · The except keyword. The finally keyword. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
Top answer
1 of 12
1240
try:
    doSomething()
except Exception: 
    pass

or

try:
    doSomething()
except: 
    pass

The difference is that the second one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from BaseException, not Exception.

See documentation for details:

  • try statement
  • exceptions

However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?

2 of 12
166

It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree it's probably OSError:

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

If you want to silently ignore that error, you would do:

try:
    shutil.rmtree(path)
except OSError:
    pass

Why? Say you (somehow) accidently pass the function an integer instead of a string, like:

shutil.rmtree(2)

It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.

If you definitely want to ignore all errors, catch Exception rather than a bare except: statement. Again, why?

Not specifying an exception catches every exception, including the SystemExit exception which for example sys.exit() uses:

>>> try:
...     sys.exit(1)
... except:
...     pass
... 
>>>

Compare this to the following, which correctly exits:

>>> try:
...     sys.exit(1)
... except Exception:
...     pass
... 
shell:~$ 

If you want to write ever better behaving code, the OSError exception can represent various errors, but in the example above we only want to ignore Errno 2, so we could be even more specific:

import errno

try:
    shutil.rmtree(path)
except OSError as e:
    if e.errno != errno.ENOENT:
        # ignore "No such file or directory", but re-raise other errors
        raise
Top answer
1 of 16
467

As you correctly guessed, there are two sides to it: Catching any error by specifying no exception type after except, and simply passing it without taking any action.

My explanation is “a bit” longer—so tl;dr it breaks down to this:

  1. Don’t catch any error. Always specify which exceptions you are prepared to recover from and only catch those.
  2. Try to avoid passing in except blocks. Unless explicitly desired, this is usually not a good sign.

But let’s go into detail:

Don’t catch any error

When using a try block, you usually do this because you know that there is a chance of an exception being thrown. As such, you also already have an approximate idea of what can break and what exception can be thrown. In such cases, you catch an exception because you can positively recover from it. That means that you are prepared for the exception and have some alternative plan which you will follow in case of that exception.

For example, when you ask for the user to input a number, you can convert the input using int() which might raise a ValueError. You can easily recover that by simply asking the user to try it again, so catching the ValueError and prompting the user again would be an appropriate plan. A different example would be if you want to read some configuration from a file, and that file happens to not exist. Because it is a configuration file, you might have some default configuration as a fallback, so the file is not exactly necessary. So catching a FileNotFoundError and simply applying the default configuration would be a good plan here. Now in both these cases, we have a very specific exception we expect and have an equally specific plan to recover from it. As such, in each case, we explicitly only except that certain exception.

However, if we were to catch everything, then—in addition to those exceptions we are prepared to recover from—there is also a chance that we get exceptions that we didn’t expect, and which we indeed cannot recover from; or shouldn’t recover from.

Let’s take the configuration file example from above. In case of a missing file, we just applied our default configuration and might decide at a later point to automatically save the configuration (so next time, the file exists). Now imagine we get a IsADirectoryError, or a PermissionError instead. In such cases, we probably do not want to continue; we could still apply our default configuration, but we later won’t be able to save the file. And it’s likely that the user meant to have a custom configuration too, so using the default values is likely not desired. So we would want to tell the user about it immediately, and probably abort the program execution too. But that’s not something we want to do somewhere deep within some small code part; this is something of application-level importance, so it should be handled at the top—so let the exception bubble up.

Another simple example is also mentioned in the Python 2 idioms document. Here, a simple typo exists in the code which causes it to break. Because we are catching every exception, we also catch NameErrors and SyntaxErrors. Both are mistakes that happen to us all while programming and both are mistakes we absolutely don’t want to include when shipping the code. But because we also caught those, we won’t even know that they occurred there and lose any help to debug it correctly.

But there are also more dangerous exceptions which we are unlikely prepared for. For example, SystemError is usually something that happens rarely and which we cannot really plan for; it means there is something more complicated going on, something that likely prevents us from continuing the current task.

In any case, it’s very unlikely that you are prepared for everything in a small-scale part of the code, so that’s really where you should only catch those exceptions you are prepared for. Some people suggest to at least catch Exception as it won’t include things like SystemExit and KeyboardInterrupt which by design are to terminate your application, but I would argue that this is still far too unspecific. There is only one place where I personally accept catching Exception or just any exception, and that is in a single global application-level exception handler which has the single purpose to log any exception we were not prepared for. That way, we can still retain as much information about unexpected exceptions, which we then can use to extend our code to handle those explicitly (if we can recover from them) or—in case of a bug—to create test cases to make sure it won’t happen again. But of course, that only works if we only ever caught those exceptions we were already expecting, so the ones we didn’t expect will naturally bubble up.

Try to avoid passing in except blocks

When explicitly catching a small selection of specific exceptions, there are many situations in which we will be fine by simply doing nothing. In such cases, just having except SomeSpecificException: pass is just fine. Most of the time though, this is not the case as we likely need some code related to the recovery process (as mentioned above). This can be for example something that retries the action again, or to set up a default value instead.

If that’s not the case though, for example, because our code is already structured to repeat until it succeeds, then just passing is good enough. Taking our example from above, we might want to ask the user to enter a number. Because we know that users like to not do what we ask them for, we might just put it into a loop in the first place, so it could look like this:

def askForNumber ():
    while True:
        try:
            return int(input('Please enter a number: '))
        except ValueError:
            pass

Because we keep trying until no exception is thrown, we don’t need to do anything special in the except block, so this is fine. But of course, one might argue that we at least want to show the user some error message to tell him why he has to repeat the input.

In many other cases though, just passing in an except is a sign that we weren’t really prepared for the exception we are catching. Unless those exceptions are simple (like ValueError or TypeError), and the reason why we can pass is obvious, try to avoid just passing. If there’s really nothing to do (and you are absolutely sure about it), then consider adding a comment why that’s the case; otherwise, expand the except block to actually include some recovery code.

except: pass

The worst offender though is the combination of both. This means that we are willingly catching any error although we are absolutely not prepared for it and we also don’t do anything about it. You at least want to log the error and also likely reraise it to still terminate the application (it’s unlikely you can continue like normal after a MemoryError). Just passing though will not only keep the application somewhat alive (depending on where you catch of course), but also throw away all the information, making it impossible to discover the error—which is especially true if you are not the one discovering it.


So the bottom line is: Catch only exceptions you really expect and are prepared to recover from; all others are likely either mistakes you should fix or something you are not prepared for anyway. Passing specific exceptions are fine if you really don’t need to do something about them. In all other cases, it’s just a sign of presumption and being lazy. And you definitely want to fix that.

2 of 16
281

The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users.

This is way too much. In your head, you're thinking "I want to ignore this network error". If something unexpected goes wrong, then your code silently continues and breaks in completely unpredictable ways that no one can debug.

That's why you should limit yourself to ignoring specifically only some errors and let the rest pass.

🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions. Practice now: Test your Python skills with interactive challenges