Explain Codes LogoExplain Codes Logo

How can I write a try/except block that catches all exceptions?

python
exception-handling
best-practices
logging
Anton ShumikhinbyAnton Shumikhin·Sep 23, 2024
TLDR

Catch-all try/except technique is achieved with Exception:

try: # your code here except Exception as error: print(f"Oh snap! Error: {error}")

This will catch most of the exceptions except system-exiting ones. It's a like a wide net but beware of the "too wide net" syndrome that can obscure the real bugs.

From theory to reality: exception handling tips

Upgrading your catch-all block

If you want your code to be bulletproof consider these tips:

  • Specify exceptions: You know what can go wrong so handle those specific exceptions like IOError or ValueError.
  • Re-raise exceptions: Use raise in your except: to allow critical issue visibility. No one likes hidden problems.

Advanced maneuvers with logs and global handlers

Do you want to take your catch-all block to a new level? Take a look at these strategies:

  • Log it all: Use logging and traceback.format_exc() for exhaustive error reporting.
  • Exception handling at the top: At your code's highest layer, embrace a try/except block to manage unexpected errors with ease.

The silent worker: the finally block

The finally: block, working behind the scenes, ensures that cleaning and restoring operations will be executed regardless of any exceptions:

  • Safe clean-up: Release locks, close files, or restore states within this block.

The else: clause

The else: clause is there to run code when no exception happens in the try: block. A little different, but definitely handy!

Additional twists: Exception hierarchy and BaseException

  • Know your hierarchy: Starting from Child Exceptions before handling Parent Exceptions lets you have control over different errors.
  • Handle with care: BaseException should be reserved for logging or re-raising, not as a default catch all.

The way of the clean coder

Follow these coding principles to write clean and understandable Python code:

  • Speak clear: Exception messages should tell exactly what went wrong.
  • Clean-up after party: Always restore your code's state after an exception.