Errors & Exception Types in Python

Module 4 • Session 27 • Allocation: 1 Contact Hr

try-except built-in errors exception hierarchy finally block fault tolerance

Errors in Python fall broadly into two main categories: compile-time parsing errors (Syntax Errors) and runtime execution faults (Exceptions). Properly detecting and handling exceptions prevents unexpected crashes and ensures software resilience.

1. Syntax Errors vs. Runtime Exceptions

Syntax errors occur when Python's parser fails to digest code grammar, blocking script execution altogether. Exceptions occur during program execution when syntactically valid code triggers an unforeseen state.

Error Category Occurs At Detection Method Can Be Caught with try/except?
Syntax Error Parsing phase Invalid code grammar (e.g., missing :) No (prevents script startup)
Exception Execution phase Runtime evaluation failures Yes (via try/except)

2. Standard Built-In Exceptions Overview

Python provides a rich built-in hierarchy inherited from the base Exception class.

# Common Built-In Exceptions in Action # 1. ZeroDivisionError # result = 10 / 0 # 2. TypeError # result = "Age: " + 25 # 3. ValueError # num = int("hello") # 4. KeyError # data = {"name": "Alice"} # value = data["age"] # 5. IndexError # items = [10, 20] # val = items[5]

3. Exception Control Structure (try - except - else - finally)

Python offers a full four-part control pattern to intercept and isolate runtime execution errors cleanly.

def parse_and_divide(val1, val2): try: num1 = float(val1) num2 = float(val2) result = num1 / num2 except ValueError as e: print(f"Conversion Error: {e}") except ZeroDivisionError: print("Division Error: Cannot divide by zero!") except Exception as e: print(f"Unexpected Error: {e}") else: print(f"Division successful! Result = {result}") finally: print("Execution complete. Cleaning up resources...") parse_and_divide(10, 2) parse_and_divide(10, 0)
Anti-Pattern Alert: Avoid using bare except: statements without specifying exception types. A bare except intercepts critical system interrupts like KeyboardInterrupt and SystemExit, making programs difficult to terminate cleanly.

4. Inspecting the Exception Object

Capturing the exception variable using as err exposes diagnostic metadata including exception arguments and stack attributes.

try: with open("non_existent_file.txt", "r") as f: content = f.read() except FileNotFoundError as err: print("Error Class:", type(err).__name__) print("Error Details:", err) print("System Error Code:", err.errno)
Base Class Knowledge: All standard non-system exceptions inherit from Exception, which itself inherits from BaseException. Catching Exception captures user-level runtime errors without trapping process termination signals.

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Safe Cast Calculator

Write a function safe_add(a, b) that attempts to add two inputs together. If a TypeError occurs, attempt to convert both arguments to floats and retry.

Challenge 2: Multi-Key Dictionary Lookup

Write a function that accepts a dictionary and a list of keys. Safe-fetch all values, returning a default message whenever a KeyError occurs for missing items.

Challenge 3: Robust Input Validator

Create a loop that continuously prompts the user for integer input using Pyodide's interactive execution, recovering gracefully from ValueError exceptions until valid data is entered.

⚡ Interactive Sandbox (Exception Playground)
Console Output:
Click "Run Code" above to execute interactive exception scripts...

📝 Knowledge Check Quiz

1. Which block in a try-except structure executes only if NO exceptions were raised?
2. What error type is raised when accessing an index that is out of bounds in a list?
3. Why should you catch `Exception` instead of using a bare `except:` clause?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)