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 errormeans: “If this specific problem happens, give the report the labelerror.”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.
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 block:
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:
- Python enters the
tryblock. textreceives the string value"twenty".int(text)attempts to convert"twenty"into an integer.- The conversion fails, so Python raises a
ValueError. - Python skips the rest of the
tryblock. Therefore,print(quantity)does not run. - The
except ValueError as errorblock matches the raised exception. - Python assigns the exception object to
error. print(...)convertserrorto its readable message and displays it.
Possible output:
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
FileNotFoundErrorwhen 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.
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.
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()
Exception error:
()
Comparisons
| Approach | What it catches or shows | Best use |
|---|---|---|
except ValueError as error | One expected error type and its message | Input conversion and validation |
except (ValueError, TypeError) as error | Any exception in a selected group | Operations that may fail in a few known ways |
except Exception as error | Most ordinary application exceptions | Top-level error reporting or a carefully scoped boundary |
Bare except: | Almost every exception, including interruption and exit signals | Rarely appropriate; avoid for normal application code |
print(error) | Short exception message | User-facing messages or quick debugging |
traceback.print_exc() |
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 errorcreates 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.
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?
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.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.