🌱 Junior Track 12 of 12

12. Error & Exception Handling

Write resilient Python code: `try`, `except`, `else`, `finally`, `Built-in Exceptions`, `raising exceptions`, `custom exceptions`, `exception chaining`, and avoiding overly broad `except` blocks.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 12 — ERROR & EXCEPTION HANDLING
# ==============================================================================

# 1. Custom Exception Class
class InvalidAgeError(ValueError):
    """Custom exception raised when user age is out of valid bounds."""
    pass

class DatabaseConnectionError(Exception):
    """Custom exception for database operation failures."""
    pass

# 2. Function with try - except - else - finally
def safe_divide(a: float, b: float) -> float | None:
    """Demonstrates complete exception handling lifecycle."""
    result = None
    try:
        result = a / b  # May raise ZeroDivisionError
    except ZeroDivisionError as err:
        print(f"[ERROR] Division failed: {err}")
    except TypeError as err:
        print(f"[ERROR] Invalid data type provided: {err}")
    else:
        print(f"[SUCCESS] Division completed. Result = {result}")
    finally:
        print("[CLEANUP] Execution of safe_divide completed.")
    return result

# 3. Raising & Exception Chaining
def register_user(name: str, age: int):
    if age < 18:
        raise InvalidAgeError(f"User '{name}' age {age} is below minimum required 18.")
    
    try:
        # Simulating database network failure
        raise ConnectionError("Socket timed out")
    except ConnectionError as err:
        # Exception Chaining using 'from'
        raise DatabaseConnectionError("Failed to persist user in DB") from err

if __name__ == "__main__":
    print("--- Test 1: Successful Division ---")
    safe_divide(10, 2)

    print("\n--- Test 2: Handling ZeroDivisionError ---")
    safe_divide(10, 0)

    print("\n--- Test 3: Custom Exception Handling ---")
    try:
        register_user("Dilshad", 16)
    except InvalidAgeError as e:
        print(f"[CAUGHT] {e}")

⭐ Rate Track 12: Exception Handling (1 to 5 Stars)

Your rating is stored directly in the database. Average: 4.9 / 5 (1 rating)

★ ★ ★ ★ ★
🌱 Junior Track 12 Master Reference

12. Python Error & Exception Handling Reference

1️⃣ Complete Exception Control Structure

try:
    val = int("42")
except ValueError as err:
    print(f"Parsing error: {err}")
else:
    print(f"Parsed integer successfully: {val}")
finally:
    print("Completed parsing attempt.")

2️⃣ Built-in Exceptions Cheat Sheet

Exception Trigger Cause Code Example
ZeroDivisionError Division or modulo by zero. 10 / 0
ValueError Valid type but inappropriate value. int("abc")
TypeError Incompatible operation on data types. "5" + 5
KeyError Accessing missing dictionary key. user_dict["missing"]
IndexError Sequence index out of range bounds. items[99]

3️⃣ Custom Exceptions & Chaining (`from`)

Create custom domain-specific exception classes by inheriting from Exception or specialized exceptions like ValueError. Use raise NewError(...) from original_err for clean traceback chaining.

class PaymentFailedError(Exception):
    pass

try:
    process_gateway_card()
except NetworkTimeout as err:
    raise PaymentFailedError("Payment gateway failed") from err

4️⃣ Best Practices: Avoiding Overly Broad `except:`

  • Never use bare except:: Bare except catches KeyboardInterrupt and SystemExit, preventing user termination.
  • Catch specific exceptions: Always target exact exception types (`ZeroDivisionError`, `ValueError`).
  • Write informative error messages: Include contextual information (e.g., variable values, user IDs) in exception messages.
🚨 Complete Python Error List, Root Causes & Production Solutions

🌱 Junior Python Core Syntax & Runtime Error Encyclopedia

Every Junior-Level (18) Python exception explained with its exact root reason, step-by-step fix, side-by-side ❌ Broken vs. ✅ Fixed Code, and 1-click Live Python Execution.

🔍
Showing Level Errors
📋 Quick-Reference Summary Table: Junior Python Errors (18)
Level Exception / Error Root Reason (Why It Happens) Production Solution (How to Fix)
JuniorSyntaxError: invalid syntax / unterminated stringRaised during the parsing stage before any line executes. Common causes include missing a colon (:) after if/for/def/class headers, unclosed parentheses/brackets, unclosed quotes, or using assignment (=) instead of equality (==) inside an if condition.Inspect the line number and caret (^) in the traceback AND the line immediately above it (unclosed parentheses often report on the next line). Add the missing colon, closing quote/bracket, or change = to ==.
JuniorIndentationError / TabError: unexpected indentPython uses whitespace indentation to define code blocks instead of curly braces {}. IndentationError occurs when a block is missing indentation after a colon, indents don't align in the same block, or tabs and spaces are mixed (TabError).Follow PEP 8 strictly: use exactly 4 spaces per indentation level and configure your IDE to convert Tabs to Spaces automatically.
JuniorNameError: name '...' is not definedOccurs when Python tries to read a variable, function, or module name that has not been assigned yet in the current scope, is misspelled (e.g., 'ture' instead of 'True'), or was only defined inside an if-branch that did not run.Initialize variables with a default value before conditional branches, verify exact case-sensitive spelling, and import required modules before using them.
JuniorTypeError: unsupported operand type(s) / not callableOccurs when an operation is applied to incompatible types (such as concatenating a str and an int: 'Score: ' + 95), passing the wrong number of arguments to a function, or shadowing a built-in function name (like naming a variable list = [1,2] or str = 'abc') and later calling list().Use f-strings for string formatting, convert input strings with int()/float() before math operations, and never name variables after built-ins (list, dict, str, sum, max, min).
JuniorValueError: invalid literal for int() / not enough values to unpackRaised when a function receives an argument of the correct type (e.g., str) but with an inappropriate value (e.g., int('42.5') or int('abc')), or when tuple unpacking has a mismatched item count (a, b = [1, 2, 3]).Validate user strings or wrap parsing in a try...except ValueError block. For flexible unpacking, use starred expressions (first, *rest = items).
JuniorIndexError: list index out of rangeAttempting to access a list, tuple, or string index that is >= len(seq) or < -len(seq). Often caused by off-by-one range loops (range(len(items) + 1)) or indexing an empty list (items[0]).Check if a sequence is non-empty (if items:) before indexing, iterate directly over elements (for item in items:), or use slicing (items[:1]) which never raises IndexError.
JuniorKeyError: 'missing_key'Raised when accessing a dictionary key via square brackets dict[key] that does not exist in the dictionary.Use dict.get(key, default) for safe lookups with a fallback value, check 'if key in my_dict:', or use collections.defaultdict when accumulating values.
JuniorAttributeError: 'NoneType' object has no attribute '...'Occurs when calling a method or accessing an attribute on an object that doesn't define it. The #1 cause for Junior developers is assigning the result of an in-place list method like my_list = my_list.sort() or my_list = my_list.append(x), which returns None!Call in-place mutating methods (.append(), .sort(), .extend(), .reverse()) on their own line without reassigning the variable, or use sorted(my_list) which returns a new list.
JuniorZeroDivisionError: division by zeroDividing any number by 0 using /, //, or % (modulo). Frequently happens when computing averages on an empty list where len(items) == 0.Always guard denominators before dividing (return 0.0 if not items else sum(items) / len(items)).
JuniorModuleNotFoundError / ImportErrorPython cannot locate the module in sys.path. Usually caused by installing a package globally while running the script in a different virtual environment (.venv), misspelling the package import name, or naming your own script file the same as a standard library module (e.g., naming your file random.py or json.py).Activate your virtual environment and install via 'python -m pip install <pkg>', and never name local .py files after standard library modules.
JuniorFileNotFoundError: [Errno 2] No such file or directoryOpening a file for reading ('r') when the path does not exist, or relying on a relative path that breaks when the script is launched from a different working directory.Use pathlib.Path(__file__).resolve().parent to anchor relative paths to the script's directory, check path.exists(), or handle FileNotFoundError cleanly.
JuniorTypeError: 'tuple' or 'str' object does not support item assignmentStrings (str) and tuples (tuple) are immutable in Python—their individual characters or elements cannot be modified in place after creation.For strings, create a new string using slicing, .replace(), or ''.join(). For collections that need item mutation, convert the tuple to a list.
JuniorTypeError: unhashable type: 'list' / 'dict' / 'set'Dictionary keys and set elements must be hashable (immutable). Mutable containers like list, dict, and set do not have a stable __hash__ value and cannot be used as dictionary keys or put inside a set.Convert mutable lists to immutable tuples (tuple(my_list)) or sets to frozenset() before using them as dictionary keys or set members.
JuniorRecursionError: maximum recursion depth exceededA recursive function calls itself infinitely because it is missing a base termination case, or the recursive step does not move closer to the base case (exceeding sys.getrecursionlimit(), default 1000 frames).Always define an explicit base case (e.g., if n <= 1: return 1) at the top of the function, or rewrite deep recursion as an iterative loop.
JuniorStopIteration (Manual next() Exhaustion)Calling built-in next(iterator) on an iterator or generator that has no more items left to yield raises StopIteration (for loops catch this automatically, but manual next() calls do not).Pass a default fallback value as the second argument to next(iterator, default) so it returns the fallback instead of raising StopIteration.
JuniorUnicodeDecodeError: 'utf-8' codec can't decode byteReading a file or byte stream encoded in Latin-1 / Windows-1252 (cp1252) using UTF-8, or omitting encoding='utf-8' on Windows where the default locale encoding differs.Always specify explicit encoding='utf-8' when opening text files, or use errors='replace' / encoding='latin-1' when ingesting legacy non-UTF-8 files.
JuniorAssertionErrorRaised when an assert statement evaluates to False. Note: never use assert for production input validation or security checks because running Python with the -O (optimize) flag strips all assert statements from bytecode!Use assert in unit tests (pytest) and internal development checks; in production code, raise explicit ValueError or TypeError instead.
JuniorTypeError: missing 1 required positional argument: 'self'Defining an instance method inside a class without 'self' as its first parameter, or calling an instance method directly on the class (MyClass.method()) without instantiating an object first (MyClass().method()).Always include 'self' as the first parameter of instance methods (or decorate with @staticmethod / @classmethod if no instance is needed) and instantiate the class with parentheses.
← 11. OOP 🌱 Junior Hub 13. File Handling →