๐ก๏ธ Python Error Handling โ try, except, finally Explained
Proper exception handling makes your Python code robust and production-ready. Learn try/except/finally with real-world patterns.
Never use bare 'except:' without specifying the exception type โ it silently swallows ALL errors including KeyboardInterrupt.
๐ป Code Example:
# 1. Basic try/except try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") # Error: division by zero # 2. Multiple exception types try: user_input = int("santoshtvk") # Simulated bad input except ValueError: print("Not a valid number") except TypeError: print("Wrong type") # 3. else + finally def fetch_pynfinity_score(user_id): try: # Simulate reading a score scores = {42: 99.5, 1: 85.0} score = scores[user_id] except KeyError: print(f"User {user_id} not found") return None else: # Runs ONLY if no exception occurred print(f"Score retrieved: {score}") return score finally: # ALWAYS runs โ perfect for cleanup print("Query complete") fetch_pynfinity_score(42) # 4. Raising custom exceptions class PynfinityAccessError(Exception): """Raised when a user tries to access premium content without subscription.""" pass def get_premium_content(user_is_premium): if not user_is_premium: raise PynfinityAccessError("Upgrade to Pynfinity Premium to access this content!") return "Here's your advanced AI course module!" try: get_premium_content(user_is_premium=False) except PynfinityAccessError as e: print(e)
| Concept | Key Takeaway |
|---|---|
| try/except | Catch and handle specific errors |
| except Exception as e | Catch any exception and access the message via e |
| else clause | Runs only if no exception โ put 'happy path' code here |
| finally clause | Always runs โ cleanup goes here |
| raise | Re-raise an exception or raise a new one |
Keep exploring and happy coding! ๐