Exception handling is essential in defensive data handling. Malicious users may attempt to exploit applications by providing invalid input to trigger vulnerabilities. Proper exception handling prevents information disclosure, maintains application stability, and provides security insights through logging.
Poor exception handling can expose sensitive information, crash applications, or create security vulnerabilities that attackers can exploit.
try: # Code that might raise an exception result = risky_operation()except ValueError as e: # Handle specific exception print(f"Invalid value: {e}")except Exception as e: # Handle any other exception print(f"Unexpected error: {e}")finally: # Always executes, useful for cleanup cleanup_resources()
import redef simple_check_password(password: str) -> bool: if not issubclass(type(password), str): return False if len(password) < 8: return False if len(password) > 20: return False if re.search(r"[ ]", password): return False if not re.search(r"[A-Z]", password): return False if not re.search(r"[a-z]", password): return False if not re.search(r"[0-9]", password): return False if not re.search(r"[@$!%*?&]", password): return False return True
A more Pythonic approach that provides detailed error messages:
import reimport bcryptdef check_password(password: str) -> bytes: if not issubclass(type(password), str): raise TypeError("Expected a string") if len(password) < 8: raise ValueError("less than 8 characters") if len(password) > 20: raise ValueError("more than 10 characters") if re.search(r"[ ]", password): raise ValueError("contains ' ' space characters") if not re.search(r"[A-Z]", password): raise ValueError("does not contain uppercase letters") if not re.search(r"[a-z]", password): raise ValueError("does not contain lowercase letters") if not re.search(r"[0-9]", password): raise ValueError("does not contain a digit '0123456789'") if not re.search(r"[@$!%*?&]", password): raise ValueError("does not contain one of '@$!%*?&' special characters") # Password is returned encoded so it can't be accidently logged in a human readable format return password.encode()
Returning the password as encoded bytes prevents accidental logging in human-readable format, adding an extra layer of security.
from flask import Flask, jsonifyapi = Flask(__name__)@api.errorhandler(400)def bad_request(error): return jsonify({ 'error': 'Bad Request', 'message': 'The request could not be understood' }), 400@api.errorhandler(404)def not_found(error): return jsonify({ 'error': 'Not Found', 'message': 'The requested resource was not found' }), 404@api.errorhandler(500)def internal_error(error): # Log the error but don't expose details to user api.logger.error(f'Server Error: {error}') return jsonify({ 'error': 'Internal Server Error', 'message': 'An unexpected error occurred' }), 500