Is it a good practice to use try-except-else in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Yes, try-except-else is a good practice in Python and is explicitly recommended in the official Python documentation and PEP 8. The else block runs only when the try block completes without raising an exception, which narrows the scope of the except clause to just the code that might actually fail. This prevents accidentally catching exceptions from code that should not be guarded, making error handling more precise and bugs easier to diagnose.
The Structure of try-except-else-finally
The execution flow is: try → except (if exception) OR else (if no exception) → finally (always). The else block is skipped entirely if an exception occurs.
Why else Makes Error Handling More Precise
Without else, the except clause covers both json.loads and save_to_database. With else, only the parsing step is guarded, and any unexpected exceptions from save_to_database propagate up the call stack where they belong.
Common Use Cases
else vs Putting Code at the End of try
Option A catches DatabaseError from both connect() and execute(). Option B catches it only from connect(). If execute() fails, the exception propagates — which may be the correct behavior if you want to handle connection errors differently from query errors.
else with finally
The finally block runs after either except or else, making it ideal for cleanup. The else block processes the successful result, while finally handles resource cleanup regardless of outcome.
When NOT to Use else
Skip else when the except block returns, raises, or breaks out of the flow. In these cases, code after the try/except only executes on success anyway.
The EAFP Principle
Python follows "Easier to Ask Forgiveness than Permission" (EAFP), which favors try/except over pre-checking conditions:
The else block complements EAFP by clearly separating the "risky" operation from the "success" path.
Common Pitfalls
- Catching too broad an exception without else: Using
except Exceptionwith code after the risky call insidetrysilently swallows errors from non-risky code. Move non-risky code toelseso only the intended operation is guarded. - Confusing else with finally:
elseruns only on success (no exception).finallyruns always (exception or not). Putting cleanup code inelsemeans it is skipped when an exception occurs, which is usually wrong for cleanup. - Using else when except already exits: If the
exceptblock callsreturn,raise, orsys.exit(), code after the try/except only runs on success. Addingelseis redundant and reduces readability. - Bare except with else:
except:(no exception type) catches everything includingKeyboardInterruptandSystemExit. This makes theelseblock unreachable for many real errors. Always specify the exception type. - Variable scoping confusion: Variables assigned in the
tryblock are accessible inelse(Python does not create a new scope fortry). But if the exception occurs before the assignment, the variable is undefined inelse, causingNameError.
Summary
try-except-elseis a recommended Python pattern that narrows exception handling scope- The
elseblock runs only whentrycompletes without exceptions - Use
elseto separate risky operations (intry) from success-path logic (inelse) - Combine with
finallyfor cleanup that must run regardless of outcome - Skip
elsewhenexceptalready exits the flow (return, raise, break) - The pattern aligns with Python's EAFP philosophy — try the operation, handle failure, then proceed on success
Related reading
- Is it bad to have my virtualenv directory inside my git repository?
- Is it not possible to define multiple constructors in Python?
- Is it ok to use dashes in Python files when trying to import them?
- Is it possible only to declare a variable without assigning any value in Python?
- Is it expensive to use try-catch blocks even if an exception is never thrown?
- Is it good practice to make the constructor throw an exception?
- Is it possible to add TransformedTargetRegressor into a scikit-learn pipeline?
- Is it possible to append Series to rows of DataFrame without making a list first?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.