Always ensure exceptions are properly raised and propagated rather than being logged and swallowed. Avoid patterns where errors are caught, logged, and then execution continues normally, as this can hide critical failures from calling code.
Always ensure exceptions are properly raised and propagated rather than being logged and swallowed. Avoid patterns where errors are caught, logged, and then execution continues normally, as this can hide critical failures from calling code.
Key principles:
except Exception:
blocks that might hide unexpected errors. When you must use broad handlers, ensure error details are preserved and re-raisedfrom None
when re-raising exceptions to prevent sensitive data (like file contents) from being captured in exception chainsExample of proper error handling:
# Bad - logs error but continues execution
try:
result = risky_operation()
except Exception as e:
logger.error(f"Error occurred: {e}")
# Execution continues, error is hidden
# Good - logs error and re-raises
try:
result = risky_operation()
except Exception as e:
logger.error(f"Error occurred: {e}")
raise # or raise specific exception type
# Good - prevents data leakage in exception chains
try:
file_text = byte_data.decode(encoding)
except (UnicodeDecodeError, UnicodeError):
raise UnprocessableEntityError(
f"File encoding detection failed: detected '{encoding}' but decode failed."
) from None # Prevents original exception with file data from being chained
This ensures that failures are communicated to calling code and can be handled appropriately, rather than being silently ignored.
Enter the URL of a public GitHub repository