Chapter 7: Exception handling

Catch all exceptions

face Josiah Wang

Technically, you can use a non-specific except as a ‘catch-all’ to handle any other types of exceptions.

try:
    a = int(input("a = "))
    b = int(input("b = "))
    print(f"a/b = {a/b}") 
except ValueError: 
    print("Cannot convert your input to a number.") 
except ZeroDivisionError: 
    print("b should not be zero.") 
except: 
    print("Something bad happened.")

PEP 8 does NOT recommend doing this. It actually says

“A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:)”

So you can use except Exception: instead, but again use it with caution! It is better to use specific exceptions to keep your code readable and make it easier to maintain your code in the future. Also keep your try blocks as small as possible and let them handle very specific errors.