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 › python_challenges_try_except.asp
Python Try...Except Code Challenge
Test your understanding of Python try...except by completing a small coding challenge.
🌐
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
🌐
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 › 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
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 ...
Find elsewhere
🌐
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 › 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
🌐
Python Basics
pythonbasics.org › try-except
Try and Except in Python - Python Tutorial
The try except statement can handle exceptions. Exceptions may happen when you run a program. Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.
🌐
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.