Python
exception handling
error handling
Python exceptions
programming tips

Getting the exception value in Python

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Exception handling in Python is most useful when you capture both the exception type and the detailed error message. The error message often explains what input failed, which key was missing, or which conversion was invalid. By extracting exception values correctly, you can log actionable diagnostics without crashing the entire application flow.

Core Sections

Capturing exception objects with as

Python binds the thrown exception instance to a variable using except SomeError as exc. This object includes message text and type specific fields. You can print it, log it, or branch on the error class.

python
1def parse_positive_int(raw: str) -> int:
2    try:
3        value = int(raw)
4        if value <= 0:
5            raise ValueError("value must be positive")
6        return value
7    except ValueError as exc:
8        print(f"Invalid input: {exc}")
9        raise
10
11for token in ["12", "-5", "abc"]:
12    try:
13        print(parse_positive_int(token))
14    except ValueError:
15        pass

This pattern preserves stack context because the original exception is re raised. If you replace it with a new exception without chaining, important debugging information can disappear.

Accessing traceback details for deeper debugging

For production systems, message text alone is rarely enough. The traceback module helps capture full call stacks. Combined with structured logging, this lets you inspect failures after deployment.

python
1import logging
2import traceback
3
4logging.basicConfig(level=logging.INFO)
5logger = logging.getLogger("app")
6
7def divide(a: float, b: float) -> float:
8    return a / b
9
10try:
11    divide(10, 0)
12except ZeroDivisionError as exc:
13    logger.error("Computation failed: %s", exc)
14    logger.error("Traceback follows
15%s", traceback.format_exc())

For web services, store this information in logs rather than returning raw traces to clients. Detailed traces can expose implementation details and create security risk.

Chaining exceptions to keep root cause

Sometimes you want a domain specific error while still keeping the original failure. Use raise NewError(...) from exc so the root cause remains visible.

python
1class ConfigError(Exception):
2    pass
3
4def load_port(config: dict) -> int:
5    try:
6        return int(config["port"])
7    except (KeyError, ValueError) as exc:
8        raise ConfigError("Invalid configuration for port") from exc
9
10try:
11    load_port({"port": "not-a-number"})
12except ConfigError as exc:
13    print(exc)
14    print(f"Root cause type: {type(exc.__cause__).__name__}")

This approach is cleaner than swallowing the original exception and writing a generic message. Good exception chains reduce time to diagnose incidents because developers can see both business context and low level cause.

Handling multiple exception types clearly

When one block can raise different errors, avoid catching Exception unless you truly need a top level safety net. Catching broad exceptions too early can hide programming mistakes and produce vague logs. Prefer specific handlers with targeted recovery behavior.

A useful pattern is to map technical exceptions to user facing messages near the application boundary. Keep internal exception values intact in logs, and translate only the response text that leaves your service.

Common Pitfalls

  • Catching Exception everywhere and hiding real bugs. Catch specific exception types at the layer that can handle them.
  • Logging only custom messages without the exception object. Include the original exception value so logs remain diagnostic.
  • Re raising a new exception without from exc, which loses root cause context. Chain exceptions intentionally.
  • Returning raw traceback details to end users. Keep detailed traces in logs and return safe messages externally.
  • Treating exception handling as control flow for normal logic. Use explicit condition checks for expected cases.

Summary

  • Use except ... as exc to capture the exception value and inspect details.
  • Keep stack context by re raising properly and using exception chaining.
  • Combine exception values with structured logging for fast debugging.
  • Catch narrow exception types and implement targeted recovery.
  • Preserve security by separating internal diagnostics from external error messages.

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.