How do I properly handle exceptions in Python try-except blocks?

wind17 IN 📗 Student 👁 29 ⚑ Report Programming

I've been writing Python for a couple years now and I'm still not sure if I should catch specific exceptions or just use a broad except clause. My current code has a lot of generic exception handlers and I'm wondering if that's actually a bad practice or if it's fine for smaller projects.

2 answers

What's your code actually doing when those exceptions hit - are you logging them, retrying, or just silently moving on?

The reason people push for specific exceptions is that a bare `except:` or `except Exception:` will catch literally everything, including stuff you didn't anticipate and probably shouldn't be swallowing. Like if you're trying to open a file and you catch `FileNotFoundError`, that's specific and makes sense. But a bare except will also catch things like `KeyboardInterrupt` or `SystemExit`, which you usually want to let through. Even worse, it hides bugs - if your code has a typo or logic error that raises something unexpected, you'll never see it because the except clause ate it.

That said, for smaller scripts or quick stuff, people get pragmatic about it. The difference really shows up when you're debugging or when your code gets handed off to someone else. Specific exceptions make your intent clear - this code knows how to handle a missing file, but not a database connection problem. If you're writing something that's going to stay small, catching `Exception` (not bare `except`) is way safer than a blanket handler, and you can at least see what's being caught. As your projects grow, you'll want to get more specific though. The practice of being deliberate about what you catch isn't just pedantic - it saves you from mysterious bugs later.

wind17 asker Currently just logging them and moving on. Mostly file I/O and API calls in small scripts, so haven't hit issues yet, but I see your point about hidden bugs.

Specific exceptions beat generic ones because you'll catch bugs you didn't mean to swallow - like a typo in a variable name that raises `NameError`, which a bare `except:` will hide instead of letting you fix it. Even for smaller projects, the habit pays off fast; you can always group related exceptions like `except (ValueError, TypeError):` if you want to keep it lean.

The real pitfall people skip over: bare `except:` even catches things like `KeyboardInterrupt` and `SystemExit`, so your program might ignore a user's Ctrl+C and keep running. Use `except Exception:` at absolute minimum if you need a catch-all, but honestly, spend 30 seconds figuring out what could actually fail and list those.

Your answer

Log into answer.