Question

Print Python Exceptions and Tracebacks in except Blocks

pythonexceptionerror-handling

Question

How can I print the error or exception details inside a Python except block?

try:
    # Code that may raise an exception
    ...
except:
    print(exception)

What should be used instead of exception so that the caught exception, and optionally its full traceback, can be printed?

Short Answer

You will learn how Python exception handling works, how to store a caught exception with as, how to print its message, and how to display a full traceback for debugging. You will also learn why a bare except: is usually too broad.

Concept

A Python exception is an object created when something goes wrong while a program runs, such as dividing by zero, reading a missing file, or converting invalid text to a number.

A try block contains code that might fail. An except block handles a matching exception so the program can respond instead of stopping immediately.

The name exception is not automatically created by Python. To access the exception object, assign it a name with as:

try:
    result = 10 / 0
except ZeroDivisionError as error:
    print(error)

error now refers to the caught ZeroDivisionError object. Converting it to text with print(error) shows its message:

division by zero

For debugging, the message alone is often not enough. A traceback shows the call stack and the exact line where the error occurred. Python's traceback module can print it.

Catching specific expected exceptions is important. It keeps error handling clear and avoids accidentally hiding serious events such as KeyboardInterrupt when a user presses Ctrl+C.

Mental Model

Think of a try block as a task being performed and an exception as a problem report produced if the task fails.

The except block is the person receiving that report:

  • except ValueError as error means: “If this specific problem happens, give the report the label error.”
  • print(error) reads the short description from the report.
  • traceback.print_exc() prints the full route the program took before the problem occurred.

Without as error, there is no variable named error or exception for your code to print.

Take Quiz

Syntax and Examples

Use except Exception as error when you want to handle ordinary application errors and print their messages.

try:
    age = int("not a number")
except ValueError as error:
    print(f"Could not read the age: {error}")

Output:

Could not read the age: invalid literal for int() with base 10: 'not a number'

You can handle a known exception type:

try:
    total = 100 / 0
except ZeroDivisionError as error:
    print(f"Calculation failed: {error}")

Or handle ordinary exceptions more generally:

try:
    run_application()
except Exception as error:
    print(f"Application error: {error}")

To print the full traceback, import traceback and call print_exc() inside the active except block:

import traceback

try:
    total = 100 / 0
except ZeroDivisionError as error:
    print(f"Short message: {error}")
    traceback.print_exc()

The traceback is normally written to standard error, while print() writes to standard output.

Step by Step Execution

Consider this code:

try:
    text = "twenty"
    quantity = int(text)
    print(quantity)
except ValueError as error:
    print(f"Invalid quantity: {error}")

Execution steps:

  1. Python enters the try block.
  2. text receives the string value "twenty".
  3. int(text) attempts to convert "twenty" into an integer.
  4. The conversion fails, so Python raises a ValueError.
  5. Python skips the rest of the try block. Therefore, print(quantity) does not run.
  6. The except ValueError as error block matches the raised exception.
  7. Python assigns the exception object to error.
  8. print(...) converts error to its readable message and displays it.

Possible output:

Invalid quantity: invalid literal for int() with base 10: 'twenty'

Real World Use Cases

  • Form input validation: Convert a submitted age, quantity, or price and explain why invalid input cannot be accepted.
  • File processing: Catch FileNotFoundError when a configuration file or uploaded file does not exist.
  • API clients: Catch network-related errors, log details, and return a useful response rather than crashing a server process.
  • Data import scripts: Record malformed rows while continuing to process valid rows.
  • Command-line tools: Show a short user-friendly error message, while optionally printing a traceback in debug mode.
Take Quiz

Real Codebase Usage

In production code, developers usually combine specific exceptions, useful context, logging, and re-raising when an error cannot safely be handled.

Validate expected failures

def parse_port(value: str) -> int:
    try:
        port = int(value)
    except ValueError as error:
        raise ValueError(f"Port must be a whole number, got {value!r}") from error

    if not 1 <= port <= 65535:
        raise ValueError("Port must be between 1 and 65535")

    return port

raise ... from error preserves the original cause in the traceback.

Log unexpected application errors

import logging

logger = logging.getLogger(__name__)

try:
    save_report()
except OSError:
    logger.exception("Could not save the report")

logger.exception(...) is designed for use inside an except block and records the full traceback in the log.

Use guard clauses after handling

def load_settings(path: str) -> dict:
    try:
        with open(path, encoding="utf-8") as file:
            return {"content": file.read()}
    except FileNotFoundError as error:
        print(f"Settings file is missing: {error}")
        return {}

The function returns a safe fallback value after the expected error is handled.

Common Mistakes

Using a name that does not exist

This fails because exception was never assigned:

try:
    1 / 0
except:
    print(exception)  # NameError

Fix it by binding the caught exception:

try:
    1 / 0
except ZeroDivisionError as error:
    print(error)

Using a bare except:

try:
    do_work()
except:
    print("Something went wrong")

A bare except: catches nearly everything, including KeyboardInterrupt and SystemExit. Prefer a specific exception, or use Exception when appropriate:

try:
    do_work()
except Exception as error:
    print(f"Something went wrong: {error}")

Catching errors that should not be ignored

Avoid silently swallowing failures:

try:
    save_data()
except Exception:
    pass

At minimum, log or report the error. Better yet, handle only the expected exception types.

Printing only the message while debugging

print(error) may not reveal the failing line or call chain. During debugging, use:

import traceback

try:
    do_work()
except Exception:
    traceback.print_exc()

Expecting the program to continue at the failed line

After an exception, Python does not resume from the exact failing statement. It transfers control to a matching except block. Decide there whether to return a fallback value, retry, continue a loop, or re-raise the error.

Comparisons

ApproachWhat it catches or showsBest use
except ValueError as errorOne expected error type and its messageInput conversion and validation
except (ValueError, TypeError) as errorAny exception in a selected groupOperations that may fail in a few known ways
except Exception as errorMost ordinary application exceptionsTop-level error reporting or a carefully scoped boundary
Bare except:Almost every exception, including interruption and exit signalsRarely appropriate; avoid for normal application code
print(error)Short exception messageUser-facing messages or quick debugging
traceback.print_exc()Full traceback of the active exceptionDebugging in scripts and development
logger.exception("message")A log message plus full tracebackProduction services and applications

A tuple lets one handler cover multiple related expected failures:

try:
    value = int(user_input)
    result = 100 / value
except (ValueError, ZeroDivisionError) as error:
    print(f"Please enter a non-zero whole number: {error}")
Take Quiz

Cheat Sheet

# Catch one expected exception and print its message
try:
    risky_operation()
except ValueError as error:
    print(error)

# Catch most ordinary exceptions
try:
    risky_operation()
except Exception as error:
    print(f"Error: {error}")

# Print a complete traceback
import traceback

try:
    risky_operation()
except Exception:
    traceback.print_exc()

# Handle more than one expected type
try:
    risky_operation()
except (ValueError, TypeError) as error:
    print(error)

# Add context and preserve the original cause
try:
    load_data()
except OSError as error:
    raise RuntimeError("Could not load application data") from error

Rules to remember:

  • as error creates the variable that holds the caught exception.
  • print(error) prints the exception's message, not necessarily its full traceback.
  • Prefer specific exception classes whenever you know what can fail.
  • Avoid bare except: in ordinary code.
  • Call traceback.print_exc() only while handling the exception, inside except.

FAQ

How do I print an exception in Python?

Bind it using as and print the variable:

except Exception as error:
    print(error)

Why does print(exception) raise NameError?

Python does not automatically create a variable named exception. You must define a name in the handler, such as except ValueError as exception:.

How do I print the full traceback in Python?

Use the standard-library traceback module inside an except block:

import traceback
traceback.print_exc()

Should I use except: or except Exception?

Usually use a specific exception type. If a broad catch is necessary, except Exception is safer than bare except: because it does not catch interruption and system-exit exceptions.

Can I catch multiple Python exceptions in one block?

Yes. Put the types in a tuple:

except (ValueError, TypeError) as error:
    print(error)

Does print(error) stop the program?

No. Printing only displays a message. What happens next depends on the rest of your except block and surrounding code.

When should I re-raise an exception?

Re-raise it when the current code cannot recover safely, or when a higher layer needs to decide how to handle it. Use raise to re-raise the current exception.

Take Quiz

Mini Project

Description

Build a small command-line score calculator that accepts text input, converts it to a number, and reports problems without crashing. This demonstrates catching a specific exception, printing its message, and showing a traceback in optional debug mode.

Goal

Create a function that returns a score category for valid numeric input and safely reports invalid input.

Requirements

  • Accept a score as a string.
  • Convert the score to an integer.
  • Reject non-numeric values with a clear message.
  • Reject scores outside the range 0 through 100.
  • Print a full traceback only when debug mode is enabled.
Take Quiz

Keep learning

Related questions

View more