Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
How to Return Success or Error as a Tuple in Python (Result Type Pattern)
Use a (bool, value) tuple as a lightweight Result type to return either a successful result or a descriptive error message from a Python function.
def divide(dividend: float, divisor: float) -> tuple[bool, float | str]:
"""Return (True, result) on success, (False, error_message) on failure."""
if divisor == 0:
return False, "Error: Division by zero"
return True, dividend / divisor
if __name__ == "__main__":
# Success case
success, r…
How to Validate JSON in Python and Catch JSONDecodeError
A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.
import json
def validate_json(json_string):
"""Try to parse JSON, return (is_valid, data_or_error)."""
try:
data = json.loads(json_string)
return True, data
except json.JSONDecodeError as e:
return False, f"Invalid JSON: {e}"
if __name__ == "__main__":
test_inputs = [
…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.