Python error handling
try except syntax
exception handling
Python programming
Python exceptions

Python try...except comma vs 'as' in except

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Modern Python uses except ExceptionType as err to bind exceptions. The comma style was valid in Python 2 and is a syntax error in Python 3.

This difference matters when maintaining old snippets or porting scripts. A direct copy from legacy code can fail at import time before tests even run.

A clean exception strategy catches only expected errors, logs context, and re-raises when the program cannot recover safely.

Core Sections

Understand the failure mode

Most short answers fix the immediate symptom but do not explain why the issue appears. In production code, that leads to patches that pass one test and fail in another environment. Start by identifying the exact boundary where control flow or data shape changes, because that boundary is usually where behavior diverges.

Before changing code, define one expected input and one expected output. This makes debugging deterministic and gives reviewers a concrete contract for the change.

Apply a repeatable implementation pattern

A solid implementation pattern should solve the current bug and provide a clear path for future maintenance. Keep configuration explicit, keep side effects near system boundaries, and isolate domain logic in testable functions.

python
1def parse_int(value: str) -> int:
2    try:
3        return int(value)
4    except ValueError as err:
5        print(f"invalid integer: {value} ({err})")
6        raise
7
8print(parse_int("42"))

This example is intentionally compact so it can be run and verified quickly. If your production setup is larger, preserve the same structure and factor environment-specific values into configuration.

Validate with a smoke test

After implementation, run a smoke test through the most important path end to end. A smoke test does not replace full coverage, but it catches many integration regressions quickly. Start with one success case, then add a focused failure case.

python
1def load_config(path: str) -> dict:
2    try:
3        with open(path, "r", encoding="utf-8") as f:
4            return {"raw": f.read()}
5    except (FileNotFoundError, PermissionError) as err:
6        raise RuntimeError(f"cannot read config at {path}") from err
7
8print(load_config("settings.txt"))

Run this validation locally and in continuous integration using the same commands. Consistent execution paths reduce configuration drift and prevent merge-time surprises.

Make the fix maintainable

Treat the change as a long-term part of the codebase, not a one-off workaround. Prefer clear naming, explicit errors, and comments only where behavior is non-obvious. Better error messages shorten incident response time because operators know what failed and what to check next.

Document assumptions near the code, such as library version, runtime constraints, timeout expectations, or concurrency model. Clear assumptions make upgrades safer and code reviews faster.

Deployment and troubleshooting checklist

Before shipping, validate the fix under the same runtime and dependency versions used in production. Many issues in this category pass local tests but fail after deployment because classpath, thread scheduling, input shape, or runtime flags differ from developer defaults. Capture those assumptions in a short checklist and keep it beside the code.

During incidents, start with one reproducible command and one known input sample. Record expected and actual output side by side, then narrow differences one layer at a time. This method avoids random trial-and-error changes and makes post-incident review much easier for the next engineer.

Common Pitfalls

  • Using Python 2 comma syntax in Python 3 fails with SyntaxError.
  • Catching broad Exception hides unrelated bugs and complicates debugging.
  • Swallowing exceptions without logging removes useful root-cause context.
  • Not chaining exceptions can lose the original traceback.
  • Returning defaults after critical failures can corrupt downstream logic.

Summary

  • Use except SomeError as err in Python 3 code.
  • Catch specific exception classes whenever possible.
  • Log meaningful context before re-raising.
  • Use exception chaining when translating errors.
  • Treat unrecoverable failures explicitly instead of hiding them.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.