Explain Codes LogoExplain Codes Logo

Why is "except: pass" a bad programming practice?

python
exception-handling
best-practices
pythonic-code
Nikita BarsukovbyNikita Barsukov·Aug 29, 2024
TLDR

Don't use except: pass—it's the programming equivalent of sweepin' dust under the rug. Seamless debuggin' needs explicit exception handling. Catch and tackle anticipated errors, don't allow the unexpected ones to sneak past you.

try: do_something_mighty() except ExpectedButObnoxiousError: handle_it_like_a_pro() except Exception as oops: log_the_uninvited_guest(oops) # Safer than dark street corners

Treading the exception jungle

Coding isn't just typing—it's talking to your computer. Exceptions are the responses from your machine, a loud "Help!" in a sea of silent executions. You are the exception handler, its savior from these tough spots.

Choose your battles wisely

except: pass is like telling your PC, "Hush, my child, ignore your worries". This overshields your code, allowing even the nastiest bugs to pass through. Catching exceptions is an art—focus on the ones you can gracefully recover from.

Hold your exception blocks tight

Write your exception handling blocks as if they were your childern— nurturing, specific, and dear:

try: walk_on_fire() except HotFeetError: cool_me_down() # Expect HotFeetError, got ice cube except ScorchedEarthError as see_you_in_hell_baby: handle_nuclear_fallout(see_you_in_hell_baby) # Catching only for ScorchedEarthError except Exception as OMGWTFBBQ: log_and_scream(OMGWTFBBQ) raise # 'Cause zombies eat brains and errors love hiding

Maintain your code's honor

Logging and re-raising exceptions: You tackle the mess, leaving breadcrumbs for your future self. except: pass is a stumbling block, where your code trips and gets amnesia, wasting resources and causing a bloody nose to your RAM.

The passing lanes

There are moon-like craters where passing is fine. Those tiny bugs that wouldn't dare disturb the serenity of your output. Just don't forget to leave a "Beware: Bugs buried here" sign for the fellow coders!

Unraveling the exception web

Look before you leap

Python's list of exceptions is not just a scary horror tale. It's the key to understanding which exceptions to catch and when. Catching BaseException is like being paranoid of breathing air—too inclusive.

Call in the Zen

The smart folks behind Python brought us The Zen of Python. It whispers "Errors should never pass silently". Don't ignore the plea from this hidden ink—errors are your debugging canary in the coal mine.

What's that crashing sound?

There it is! That's your code falling apart because of some ignored exceptions. Silent exceptions cause random fireworks, turning the data you treasure into a mess of gibberish.

Code-review monks say: Always improve

Refinement is progress. Put on your robe, hold your code under the morning sunlight and ask, "What can I do better?" Review. Refine. Repeat. Update your exception handling accordingly.