Exception handling is a crucial concept in Python that allows you to handle errors gracefully instead of letting your program crash. In this tutorial, you’ll learn:
What exceptions are and why they matter
How to catch and handle exceptions
The difference between try-except, try-except-else, and try-except-finally
Best practices for robust error handling
10.2 Understanding Exceptions
10.3 What is an Exception?
An exception is an error that occurs during program execution. When Python encounters an error, it “raises” an exception and stops the program unless you handle it.
Common Exception Types
# Let's see some common exceptions (we'll catch them later!)# Example 1: ZeroDivisionErrortry: result =10/0exceptZeroDivisionErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")
Error: division by zero
Type: ZeroDivisionError
# Example 2: ValueErrortry: number =int("hello")exceptValueErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")
Error: invalid literal for int() with base 10: 'hello'
Type: ValueError
# Example 3: FileNotFoundErrortry:withopen("nonexistent_file.txt", "r") as f: content = f.read()exceptFileNotFoundErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")
Error: [Errno 2] No such file or directory: 'nonexistent_file.txt'
Type: FileNotFoundError
# Example 4: KeyError (dictionary)try: my_dict = {"name": "Alice", "age": 25}print(my_dict["address"])exceptKeyErroras e:print(f"Error: Key {e} not found")print(f"Type: {type(e).__name__}")
# This would crash the programage =int(input("Enter your age: ")) # User enters "twenty"# Program crashes with ValueError!
With exception handling:
# Safe versiontry: age_input ="twenty"# Simulating user input age =int(age_input)print(f"Your age is {age}")exceptValueError:print("Please enter a valid number!") age =None
Please enter a valid number!
10.5 Basic Try-Except
The try-except block is the foundation of exception handling.
10.6 Basic Syntax
try:# Code that might raise an exception risky_operation()except ExceptionType:# Code to handle the exception handle_error()
10.7 Simple Example
# Division calculatordef divide(a, b):try: result = a / breturn resultexceptZeroDivisionError:print("Error: Cannot divide by zero!")returnNoneprint(divide(10, 2)) # Works fineprint(divide(10, 0)) # Handles error gracefully
5.0
Error: Cannot divide by zero!
None
10.8 Catching the Exception Object
# Access error detailstry: number =int("not a number")exceptValueErroras e:print(f"Caught an error: {e}")print(f"Error type: {type(e).__name__}")
Caught an error: invalid literal for int() with base 10: 'not a number'
Error type: ValueError
10.9 Real-World Example: Reading Files
def read_file_safely(filename):try:withopen(filename, 'r') asfile: content =file.read()return contentexceptFileNotFoundError:print(f"Error: The file '{filename}' was not found.")returnNone# Test with existing filecontent = read_file_safely('data/sample.txt')if content:print(f"File read successfully! ({len(content)} characters)")# Test with non-existent filecontent = read_file_safely('data/missing.txt')
File read successfully! (127 characters)
Error: The file 'data/missing.txt' was not found.
10.10 Multiple Exception Handlers
You can catch different types of exceptions separately.
10.11 Multiple Except Blocks
def process_number(value):try:# Convert to integer num =int(value)# Divide 100 by the number result =100/ numreturn resultexceptValueError:print(f"Error: '{value}' is not a valid number")returnNoneexceptZeroDivisionError:print("Error: Cannot divide by zero")returnNone# Test different scenariosprint(process_number("20")) # Success: 5.0print(process_number("hello")) # ValueErrorprint(process_number("0")) # ZeroDivisionError
5.0
Error: 'hello' is not a valid number
None
Error: Cannot divide by zero
None
5.0
Error occurred: ValueError - invalid literal for int() with base 10: 'abc'
None
Error occurred: ZeroDivisionError - division by zero
None
10.13 Catch-All Exception Handler
def risky_operation(value):try:# Multiple things that could go wrong num =int(value) result =100/ num my_list = [1, 2, 3]return my_list[num]exceptValueError:print("Invalid number format")exceptZeroDivisionError:print("Cannot divide by zero")exceptIndexError:print("Index out of range")exceptExceptionas e:# Catches any other exceptionprint(f"Unexpected error: {type(e).__name__} - {e}")risky_operation("2") # Successrisky_operation("abc") # ValueErrorrisky_operation("0") # ZeroDivisionErrorrisky_operation("10") # IndexError
Invalid number format
Cannot divide by zero
Index out of range
10.14 Try-Except-Else
The else block runs only if no exception occurred in the try block.
10.15 Syntax
try:# Code that might raise an exception risky_code()except ExceptionType:# Handle the exception handle_error()else:# Runs only if no exception occurred success_code()
10.16 Basic Example
def divide_with_else(a, b):try: result = a / bexceptZeroDivisionError:print("Error: Division by zero!")else:print(f"Success! {a} / {b} = {result}")return resultdivide_with_else(10, 2)divide_with_else(10, 0)
Success! 10 / 2 = 5.0
Error: Division by zero!
10.17 File Processing Example
def process_file(filename):try:withopen(filename, 'r') asfile: content =file.read()exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNoneelse:# Only runs if file was opened successfullyprint(f"File read successfully!") lines = content.split('\n')print(f"Number of lines: {len(lines)}")return lines# Test both scenariosprint("\nTest 1 - Existing file:")result = process_file('data/sample.txt')print("\nTest 2 - Missing file:")result = process_file('data/nonexistent.txt')
Test 1 - Existing file:
File read successfully!
Number of lines: 6
Test 2 - Missing file:
Error: File 'data/nonexistent.txt' not found
10.18 Why Use Else?
The else block makes code clearer by separating: - try: Code that might fail - except: Error handling - else: Success handling
import jsondef load_config(filename):try:withopen(filename, 'r') asfile: config = json.load(file)exceptFileNotFoundError:print("Config file not found, using defaults") config = {"default": True}except json.JSONDecodeError:print("Invalid JSON format, using defaults") config = {"default": True}else:print("Configuration loaded successfully!")print(f"Config keys: {list(config.keys())}")return config# Test with valid JSONresult = load_config('data/inventory.json')
The finally block always runs, whether an exception occurred or not. It’s perfect for cleanup operations.
10.20 Syntax
try:# Code that might raise an exception risky_code()except ExceptionType:# Handle the exception handle_error()finally:# Always runs (cleanup code) cleanup()
10.21 Basic Example
def demonstrate_finally(value):try: result =10/ valueprint(f"Result: {result}")exceptZeroDivisionError:print("Error: Division by zero")finally:print("This always runs, no matter what!")demonstrate_finally(2) # Successprint()demonstrate_finally(0) # Error
Result: 5.0
This always runs, no matter what!
Error: Division by zero
This always runs, no matter what!
10.22 File Handling Example
def read_file_with_finally(filename):file=Nonetry:print(f"Opening {filename}...")file=open(filename, 'r') content =file.read()print(f"Read {len(content)} characters")return contentexceptFileNotFoundError:print(f"Error: File not found")returnNonefinally:# Ensure file is closed even if error occursiffile:file.close()print("File closed")else:print("No file to close")print("Test 1:")read_file_with_finally('data/sample.txt')print("\nTest 2:")read_file_with_finally('data/missing.txt')
Test 1:
Opening data/sample.txt...
Read 127 characters
File closed
Test 2:
Opening data/missing.txt...
Error: File not found
No file to close
Note: With with statement, you don’t need finally for files:
# The 'with' statement handles cleanup automaticallytry:withopen('data/sample.txt', 'r') asfile: content =file.read()exceptFileNotFoundError:print("File not found")# File is automatically closed here
Let’s process a file with mixed valid and invalid numbers:
# Read and process numbers from filedef process_numbers(filename): valid_numbers = [] invalid_entries = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line: # Skip empty linescontinuetry: number =float(line) valid_numbers.append(number)exceptValueError: invalid_entries.append((line_num, line))exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNone, Noneelse:print(f"Processed {len(valid_numbers)} valid numbers")print(f"Found {len(invalid_entries)} invalid entries")return valid_numbers, invalid_entries# Process the numbers filenumbers, errors = process_numbers('data/numbers.txt')if numbers isnotNone:print(f"\nValid numbers: {numbers}")print(f"Invalid entries: {errors}")print(f"Sum of valid numbers: {sum(numbers)}")
Error: File 'data/numbers.txt' not found
10.26 Configuration Parser
def parse_config(filename): config = {} errors = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line or line.startswith('#'):continuetry: key, value = line.split('=') key = key.strip() value = value.strip()# Try to convert to inttry: config[key] =int(value)exceptValueError:# Keep as string if not a number config[key] = valueexceptValueError: errors.append(f"Line {line_num}: Invalid format")exceptFileNotFoundError:print(f"Error: Config file not found")returnNoneelse:if errors:print("Warnings during parsing:")for error in errors:print(f" - {error}")return configconfig = parse_config('data/config.txt')print("\nParsed configuration:")for key, value in config.items():print(f" {key}: {value} (type: {type(value).__name__})")
def get_valid_age(age_str, max_attempts=3):""" Validate age input with retry logic """for attempt inrange(max_attempts):try: age =int(age_str)if age <0:raiseValueError("Age cannot be negative")if age >150:raiseValueError("Age seems unrealistic")exceptValueErroras e:print(f"Attempt {attempt +1}: Invalid input - {e}")if attempt < max_attempts -1:# In real scenario, would ask for new input age_str ="25"# Simulated correctionprint(f" (Retrying with: {age_str})")else:print("Max attempts reached")returnNoneelse:print(f"Valid age accepted: {age}")return agereturnNone# Test various scenariosprint("Test 1 - Invalid then valid:")get_valid_age("abc")print("\nTest 2 - Negative age:")get_valid_age("-5")print("\nTest 3 - Valid age:")get_valid_age("25")
Test 1 - Invalid then valid:
Attempt 1: Invalid input - invalid literal for int() with base 10: 'abc'
(Retrying with: 25)
Valid age accepted: 25
Test 2 - Negative age:
Attempt 1: Invalid input - Age cannot be negative
(Retrying with: 25)
Valid age accepted: 25
Test 3 - Valid age:
Valid age accepted: 25
25
10.28 Raising Exceptions
You can raise exceptions yourself to signal errors.
10.29 Basic Raise
def validate_age(age):if age <0:raiseValueError("Age cannot be negative")if age >150:raiseValueError("Age must be realistic")returnTruetry: validate_age(25) # OKprint("Age 25 is valid") validate_age(-5) # Raises errorexceptValueErroras e:print(f"Validation error: {e}")
Age 25 is valid
Validation error: Age cannot be negative
10.30 Re-raising Exceptions
def process_data(value):try: result =int(value) /10exceptValueErroras e:print(f"Logging error: {e}")raise# Re-raise the same exceptionreturn resulttry: process_data("invalid")exceptValueError:print("Caught re-raised exception in outer handler")
Logging error: invalid literal for int() with base 10: 'invalid'
Caught re-raised exception in outer handler
10.31 Custom Exceptions
# Define custom exceptionclass InsufficientFundsError(Exception):"""Raised when account has insufficient funds"""passclass BankAccount:def__init__(self, balance=0):self.balance = balancedef withdraw(self, amount):if amount >self.balance:raise InsufficientFundsError(f"Cannot withdraw ${amount}. Balance: ${self.balance}" )self.balance -= amountreturnself.balance# Use custom exceptionaccount = BankAccount(100)try: account.withdraw(50)print(f"Withdrew $50. Balance: ${account.balance}") account.withdraw(100) # This will failexcept InsufficientFundsError as e:print(f"Transaction failed: {e}")
# GOOD - Specific exception handlingdef read_json_file(filename):try:withopen(filename, 'r') asfile: data = json.load(file)exceptFileNotFoundError:print(f"File {filename} not found")except json.JSONDecodeError:print(f"Invalid JSON in {filename}")exceptPermissionError:print(f"No permission to read {filename}")returnNone# AVOID - Too broaddef read_json_bad(filename):try:withopen(filename, 'r') asfile: data = json.load(file)exceptException: # Too broad!print("Something went wrong")returnNone
10.34 Don’t Ignore Exceptions
# BAD - Silent failuretry: result =10/0except:pass# Error is hidden!# GOOD - At least log ittry: result =10/0exceptZeroDivisionErroras e:print(f"Error occurred: {e}") result =None
Error occurred: division by zero
10.35 Use Finally for Cleanup
import osdef process_file_safely(filename):file=None temp_file ="temp_processing.txt"try:file=open(filename, 'r') content =file.read()# Create temp filewithopen(temp_file, 'w') as tf: tf.write(content.upper())returnTrueexceptExceptionas e:print(f"Error: {e}")returnFalsefinally:# Cleanupiffile:file.close()# Remove temp file if it existsif os.path.exists(temp_file): os.remove(temp_file)print("Temp file cleaned up")
10.36 Provide Context in Error Messages
def divide_list_elements(numbers, divisor): results = []for i, num inenumerate(numbers):try: result = num / divisor results.append(result)exceptZeroDivisionError:# Provide context: which element, what valueprint(f"Error at index {i}: Cannot divide {num} by zero") results.append(None)exceptTypeError:print(f"Error at index {i}: {num} is not a number") results.append(None)return resultsnumbers = [10, 20, "30", 40]results = divide_list_elements(numbers, 0)print(f"Results: {results}")
Error at index 0: Cannot divide 10 by zero
Error at index 1: Cannot divide 20 by zero
Error at index 2: 30 is not a number
Error at index 3: Cannot divide 40 by zero
Results: [None, None, None, None]
10.37 Exercises
10.38 Exercise 1: Safe Calculator
Task: Create a calculator function that: 1. Takes two numbers and an operation (+, -, *, /) 2. Handles division by zero 3. Handles invalid operations 4. Uses try-except-else
def calculator(num1, num2, operation):# Your code herepass# Test casesprint(calculator(10, 5, '+')) # Should return 15print(calculator(10, 5, '/')) # Should return 2.0print(calculator(10, 0, '/')) # Should handle division by zeroprint(calculator(10, 5, '^')) # Should handle invalid operation
Solution:
Click to show solution
def calculator(num1, num2, operation):try:if operation =='+': result = num1 + num2elif operation =='-': result = num1 - num2elif operation =='*': result = num1 * num2elif operation =='/': result = num1 / num2else:raiseValueError(f"Invalid operation: {operation}")exceptZeroDivisionError:print("Error: Cannot divide by zero")returnNoneexceptValueErroras e:print(f"Error: {e}")returnNoneelse:print(f"Success: {num1}{operation}{num2} = {result}")return result# Test casescalculator(10, 5, '+')calculator(10, 5, '/')calculator(10, 0, '/')calculator(10, 5, '^')
Task: Write a function that: 1. Reads a file with numbers (one per line) 2. Calculates sum, average, min, max 3. Handles file not found 4. Handles non-numeric values 5. Uses try-except-else-finally
def file_statistics(filename):# Your code herepassfile_statistics('data/numbers.txt')
Solution:
Click to show solution
def file_statistics(filename): numbers = [] errors =0try:withopen(filename, 'r') asfile:for line infile: line = line.strip()ifnot line:continuetry: number =float(line) numbers.append(number)exceptValueError: errors +=1exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNoneelse:if numbers: stats = {'count': len(numbers),'sum': sum(numbers),'average': sum(numbers) /len(numbers),'min': min(numbers),'max': max(numbers) }print(f"Successfully processed {len(numbers)} numbers")if errors:print(f"Skipped {errors} invalid entries")return statselse:print("No valid numbers found")returnNonefinally:print("File processing complete")stats = file_statistics('data/numbers.txt')if stats:print("\nStatistics:")for key, value in stats.items():print(f" {key}: {value}")
Error: File 'data/numbers.txt' not found
File processing complete
10.40 Exercise 3: Score Parser
Task: Create a function that: 1. Reads data/scores.txt (format: “Name:Score”) 2. Parses each line into a dictionary 3. Handles missing scores (empty after colon) 4. Handles invalid score values 5. Returns valid scores and lists errors
def parse_scores(filename):# Your code herepassscores, errors = parse_scores('data/scores.txt')
Solution:
Click to show solution
def parse_scores(filename): scores = {} errors = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line:continuetry:# Split by colon name, score_str = line.split(':') name = name.strip() score_str = score_str.strip()# Handle empty scoreifnot score_str:raiseValueError("Missing score")# Convert to int score =int(score_str)# Validate score rangeif score <0or score >100:raiseValueError("Score out of range (0-100)") scores[name] = scoreexceptValueErroras e: error_msg =f"Line {line_num} ({line}): {e}" errors.append(error_msg)exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNone, Noneelse:print(f"Parsed {len(scores)} valid scores")if errors:print(f"Found {len(errors)} errors")return scores, errorsscores, errors = parse_scores('data/scores.txt')if scores isnotNone:print("\nValid Scores:")for name, score in scores.items():print(f" {name}: {score}")if errors:print("\nErrors:")for error in errors:print(f" - {error}")
Error: File 'data/scores.txt' not found
10.41 Exercise 4: Robust JSON Loader
Task: Create a function that: 1. Tries to load a JSON file 2. If file not found, creates it with default data 3. If JSON is invalid, backs up the corrupted file and creates new one 4. Returns the loaded or created data 5. Uses try-except-else-finally
import jsonimport osfrom datetime import datetimedef load_or_create_json(filename, default_data=None):if default_data isNone: default_data = {} data =None operation =Nonetry:withopen(filename, 'r') asfile: data = json.load(file) operation ="loaded"exceptFileNotFoundError:print(f"File not found. Creating {filename} with defaults.") data = default_data operation ="created"except json.JSONDecodeError as e:print(f"Invalid JSON in {filename}: {e}")# Backup corrupted file backup_name =f"{filename}.corrupted.{datetime.now().strftime('%Y%m%d_%H%M%S')}"if os.path.exists(filename): os.rename(filename, backup_name)print(f"Corrupted file backed up to: {backup_name}") data = default_data operation ="recreated"else:print(f"Successfully loaded {filename}")finally:# Save data if it was created or recreatedif operation in ["created", "recreated"]:try:withopen(filename, 'w') asfile: json.dump(data, file, indent=2)print(f"Saved {filename}")exceptExceptionas e:print(f"Error saving file: {e}")return data# Test the functiondefault_settings = {'theme': 'light', 'language': 'en', 'notifications': True}data = load_or_create_json('exercises/settings.json', default_settings)print(f"\nData: {json.dumps(data, indent=2)}")
Task: Create a comprehensive data validation system: 1. Define custom exceptions for different validation errors 2. Validate user data (age, email format, username length) 3. Collect all validation errors (don’t stop at first error) 4. Return valid data or raise exception with all errors
class ValidationError(Exception):passdef validate_user_data(data):# Your code herepass# Test datatest_users = [ {"username": "alice", "age": 25, "email": "alice@example.com"}, {"username": "ab", "age": -5, "email": "invalid-email"}, {"username": "bob_smith", "age": 30, "email": "bob@example.com"}]
Solution:
Click to show solution
import reclass ValidationError(Exception):"""Custom exception for validation errors"""passclass InvalidAgeError(ValidationError):passclass InvalidEmailError(ValidationError):passclass InvalidUsernameError(ValidationError):passdef validate_user_data(data):""" Validate user data dictionary. Raises ValidationError with all issues found. """ errors = []# Validate usernametry: username = data.get('username', '')iflen(username) <3:raise InvalidUsernameError("Username must be at least 3 characters")iflen(username) >20:raise InvalidUsernameError("Username must be at most 20 characters")ifnot username.replace('_', '').isalnum():raise InvalidUsernameError("Username can only contain letters, numbers, and underscores")except InvalidUsernameError as e: errors.append(f"Username: {e}")# Validate agetry: age = data.get('age')if age isNone:raise InvalidAgeError("Age is required")ifnotisinstance(age, int):raise InvalidAgeError("Age must be an integer")if age <0:raise InvalidAgeError("Age cannot be negative")if age >150:raise InvalidAgeError("Age must be realistic")except InvalidAgeError as e: errors.append(f"Age: {e}")# Validate emailtry: email = data.get('email', '')# Simple email regex email_pattern =r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'ifnot re.match(email_pattern, email):raise InvalidEmailError("Invalid email format")except InvalidEmailError as e: errors.append(f"Email: {e}")# If there are errors, raise exception with all of themif errors: error_message ="Validation failed:\n - "+"\n - ".join(errors)raise ValidationError(error_message)returnTrue# Test with multiple userstest_users = [ {"username": "alice", "age": 25, "email": "alice@example.com"}, {"username": "ab", "age": -5, "email": "invalid-email"}, {"username": "bob_smith", "age": 30, "email": "bob@example.com"}, {"username": "x", "age": 200, "email": "notemail"}]for i, user inenumerate(test_users, 1):print(f"\nValidating user {i}: {user['username']}")try: validate_user_data(user)print(" ✓ Validation passed!")except ValidationError as e:print(f" ✗ {e}")
Validating user 1: alice
✓ Validation passed!
Validating user 2: ab
✗ Validation failed:
- Username: Username must be at least 3 characters
- Age: Age cannot be negative
- Email: Invalid email format
Validating user 3: bob_smith
✓ Validation passed!
Validating user 4: x
✗ Validation failed:
- Username: Username must be at least 3 characters
- Age: Age must be realistic
- Email: Invalid email format
11 10. Summary
Congratulations! You’ve learned comprehensive exception handling in Python.
11.1 Key Takeaways
Exceptions are errors that occur during program execution
try-except catches and handles specific exceptions
try-except-else runs code only when no exception occurs
---title: "Exception Handling"jupyter: python3execute: eval: true echo: true warning: false---## IntroductionException handling is a crucial concept in Python that allows you to handle errors gracefully instead of letting your program crash. In this tutorial, you'll learn:- What exceptions are and why they matter- How to catch and handle exceptions- The difference between `try-except`, `try-except-else`, and `try-except-finally`- Best practices for robust error handling---## Understanding Exceptions## What is an Exception?An **exception** is an error that occurs during program execution. When Python encounters an error, it "raises" an exception and stops the program unless you handle it.### Common Exception Types {.unnumbered}```{python}# Let's see some common exceptions (we'll catch them later!)# Example 1: ZeroDivisionErrortry: result =10/0exceptZeroDivisionErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")``````{python}# Example 2: ValueErrortry: number =int("hello")exceptValueErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")``````{python}# Example 3: FileNotFoundErrortry:withopen("nonexistent_file.txt", "r") as f: content = f.read()exceptFileNotFoundErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")``````{python}# Example 4: KeyError (dictionary)try: my_dict = {"name": "Alice", "age": 25}print(my_dict["address"])exceptKeyErroras e:print(f"Error: Key {e} not found")print(f"Type: {type(e).__name__}")``````{python}# Example 5: IndexError (list)try: my_list = [1, 2, 3]print(my_list[10])exceptIndexErroras e:print(f"Error: {e}")print(f"Type: {type(e).__name__}")```## Why Handle Exceptions?**Without exception handling:**```{python}#| eval: false# This would crash the programage =int(input("Enter your age: ")) # User enters "twenty"# Program crashes with ValueError!```**With exception handling:**```{python}# Safe versiontry: age_input ="twenty"# Simulating user input age =int(age_input)print(f"Your age is {age}")exceptValueError:print("Please enter a valid number!") age =None```---## Basic Try-ExceptThe `try-except` block is the foundation of exception handling.## Basic Syntax```pythontry:# Code that might raise an exception risky_operation()except ExceptionType:# Code to handle the exception handle_error()```## Simple Example```{python}# Division calculatordef divide(a, b):try: result = a / breturn resultexceptZeroDivisionError:print("Error: Cannot divide by zero!")returnNoneprint(divide(10, 2)) # Works fineprint(divide(10, 0)) # Handles error gracefully```## Catching the Exception Object```{python}# Access error detailstry: number =int("not a number")exceptValueErroras e:print(f"Caught an error: {e}")print(f"Error type: {type(e).__name__}")```## Real-World Example: Reading Files```{python}def read_file_safely(filename):try:withopen(filename, 'r') asfile: content =file.read()return contentexceptFileNotFoundError:print(f"Error: The file '{filename}' was not found.")returnNone# Test with existing filecontent = read_file_safely('data/sample.txt')if content:print(f"File read successfully! ({len(content)} characters)")# Test with non-existent filecontent = read_file_safely('data/missing.txt')```---## Multiple Exception HandlersYou can catch different types of exceptions separately.## Multiple Except Blocks```{python}def process_number(value):try:# Convert to integer num =int(value)# Divide 100 by the number result =100/ numreturn resultexceptValueError:print(f"Error: '{value}' is not a valid number")returnNoneexceptZeroDivisionError:print("Error: Cannot divide by zero")returnNone# Test different scenariosprint(process_number("20")) # Success: 5.0print(process_number("hello")) # ValueErrorprint(process_number("0")) # ZeroDivisionError```## Catching Multiple Exceptions Together```{python}def safe_division(a, b):try: result =int(a) /int(b)return resultexcept (ValueError, ZeroDivisionError) as e:print(f"Error occurred: {type(e).__name__} - {e}")returnNoneprint(safe_division("10", "2")) # Successprint(safe_division("10", "abc")) # ValueErrorprint(safe_division("10", "0")) # ZeroDivisionError```## Catch-All Exception Handler```{python}def risky_operation(value):try:# Multiple things that could go wrong num =int(value) result =100/ num my_list = [1, 2, 3]return my_list[num]exceptValueError:print("Invalid number format")exceptZeroDivisionError:print("Cannot divide by zero")exceptIndexError:print("Index out of range")exceptExceptionas e:# Catches any other exceptionprint(f"Unexpected error: {type(e).__name__} - {e}")risky_operation("2") # Successrisky_operation("abc") # ValueErrorrisky_operation("0") # ZeroDivisionErrorrisky_operation("10") # IndexError```---## Try-Except-ElseThe `else` block runs **only if no exception occurred** in the try block.## Syntax```pythontry:# Code that might raise an exception risky_code()except ExceptionType:# Handle the exception handle_error()else:# Runs only if no exception occurred success_code()```## Basic Example```{python}def divide_with_else(a, b):try: result = a / bexceptZeroDivisionError:print("Error: Division by zero!")else:print(f"Success! {a} / {b} = {result}")return resultdivide_with_else(10, 2)divide_with_else(10, 0)```## File Processing Example```{python}def process_file(filename):try:withopen(filename, 'r') asfile: content =file.read()exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNoneelse:# Only runs if file was opened successfullyprint(f"File read successfully!") lines = content.split('\n')print(f"Number of lines: {len(lines)}")return lines# Test both scenariosprint("\nTest 1 - Existing file:")result = process_file('data/sample.txt')print("\nTest 2 - Missing file:")result = process_file('data/nonexistent.txt')```## Why Use Else?The `else` block makes code clearer by separating:- **try**: Code that might fail- **except**: Error handling- **else**: Success handling```{python}import jsondef load_config(filename):try:withopen(filename, 'r') asfile: config = json.load(file)exceptFileNotFoundError:print("Config file not found, using defaults") config = {"default": True}except json.JSONDecodeError:print("Invalid JSON format, using defaults") config = {"default": True}else:print("Configuration loaded successfully!")print(f"Config keys: {list(config.keys())}")return config# Test with valid JSONresult = load_config('data/inventory.json')```---## Try-Except-FinallyThe `finally` block **always runs**, whether an exception occurred or not. It's perfect for cleanup operations.## Syntax```pythontry:# Code that might raise an exception risky_code()except ExceptionType:# Handle the exception handle_error()finally:# Always runs (cleanup code) cleanup()```## Basic Example```{python}def demonstrate_finally(value):try: result =10/ valueprint(f"Result: {result}")exceptZeroDivisionError:print("Error: Division by zero")finally:print("This always runs, no matter what!")demonstrate_finally(2) # Successprint()demonstrate_finally(0) # Error```## File Handling Example```{python}def read_file_with_finally(filename):file=Nonetry:print(f"Opening {filename}...")file=open(filename, 'r') content =file.read()print(f"Read {len(content)} characters")return contentexceptFileNotFoundError:print(f"Error: File not found")returnNonefinally:# Ensure file is closed even if error occursiffile:file.close()print("File closed")else:print("No file to close")print("Test 1:")read_file_with_finally('data/sample.txt')print("\nTest 2:")read_file_with_finally('data/missing.txt')```**Note:** With `with` statement, you don't need finally for files:```{python}# The 'with' statement handles cleanup automaticallytry:withopen('data/sample.txt', 'r') asfile: content =file.read()exceptFileNotFoundError:print("File not found")# File is automatically closed here```## All Together: Try-Except-Else-Finally```{python}def complete_example(filename):print(f"\n--- Processing {filename} ---")try:withopen(filename, 'r') asfile: content =file.read() lines = content.split('\n')exceptFileNotFoundError:print("ERROR: File not found") lines = []else:print(f"SUCCESS: Read {len(lines)} lines")finally:print("CLEANUP: Processing complete")return linescomplete_example('data/sample.txt')complete_example('data/missing.txt')```---## Practical Examples## Processing Numeric DataLet's process a file with mixed valid and invalid numbers:```{python}# Read and process numbers from filedef process_numbers(filename): valid_numbers = [] invalid_entries = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line: # Skip empty linescontinuetry: number =float(line) valid_numbers.append(number)exceptValueError: invalid_entries.append((line_num, line))exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNone, Noneelse:print(f"Processed {len(valid_numbers)} valid numbers")print(f"Found {len(invalid_entries)} invalid entries")return valid_numbers, invalid_entries# Process the numbers filenumbers, errors = process_numbers('data/numbers.txt')if numbers isnotNone:print(f"\nValid numbers: {numbers}")print(f"Invalid entries: {errors}")print(f"Sum of valid numbers: {sum(numbers)}")```## Configuration Parser```{python}def parse_config(filename): config = {} errors = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line or line.startswith('#'):continuetry: key, value = line.split('=') key = key.strip() value = value.strip()# Try to convert to inttry: config[key] =int(value)exceptValueError:# Keep as string if not a number config[key] = valueexceptValueError: errors.append(f"Line {line_num}: Invalid format")exceptFileNotFoundError:print(f"Error: Config file not found")returnNoneelse:if errors:print("Warnings during parsing:")for error in errors:print(f" - {error}")return configconfig = parse_config('data/config.txt')print("\nParsed configuration:")for key, value in config.items():print(f" {key}: {value} (type: {type(value).__name__})")```## User Input Validation```{python}def get_valid_age(age_str, max_attempts=3):""" Validate age input with retry logic """for attempt inrange(max_attempts):try: age =int(age_str)if age <0:raiseValueError("Age cannot be negative")if age >150:raiseValueError("Age seems unrealistic")exceptValueErroras e:print(f"Attempt {attempt +1}: Invalid input - {e}")if attempt < max_attempts -1:# In real scenario, would ask for new input age_str ="25"# Simulated correctionprint(f" (Retrying with: {age_str})")else:print("Max attempts reached")returnNoneelse:print(f"Valid age accepted: {age}")return agereturnNone# Test various scenariosprint("Test 1 - Invalid then valid:")get_valid_age("abc")print("\nTest 2 - Negative age:")get_valid_age("-5")print("\nTest 3 - Valid age:")get_valid_age("25")```---## Raising ExceptionsYou can raise exceptions yourself to signal errors.## Basic Raise```{python}def validate_age(age):if age <0:raiseValueError("Age cannot be negative")if age >150:raiseValueError("Age must be realistic")returnTruetry: validate_age(25) # OKprint("Age 25 is valid") validate_age(-5) # Raises errorexceptValueErroras e:print(f"Validation error: {e}")```## Re-raising Exceptions```{python}def process_data(value):try: result =int(value) /10exceptValueErroras e:print(f"Logging error: {e}")raise# Re-raise the same exceptionreturn resulttry: process_data("invalid")exceptValueError:print("Caught re-raised exception in outer handler")```## Custom Exceptions```{python}# Define custom exceptionclass InsufficientFundsError(Exception):"""Raised when account has insufficient funds"""passclass BankAccount:def__init__(self, balance=0):self.balance = balancedef withdraw(self, amount):if amount >self.balance:raise InsufficientFundsError(f"Cannot withdraw ${amount}. Balance: ${self.balance}" )self.balance -= amountreturnself.balance# Use custom exceptionaccount = BankAccount(100)try: account.withdraw(50)print(f"Withdrew $50. Balance: ${account.balance}") account.withdraw(100) # This will failexcept InsufficientFundsError as e:print(f"Transaction failed: {e}")```---## Best Practices## Be Specific with Exceptions```{python}# GOOD - Specific exception handlingdef read_json_file(filename):try:withopen(filename, 'r') asfile: data = json.load(file)exceptFileNotFoundError:print(f"File {filename} not found")except json.JSONDecodeError:print(f"Invalid JSON in {filename}")exceptPermissionError:print(f"No permission to read {filename}")returnNone# AVOID - Too broaddef read_json_bad(filename):try:withopen(filename, 'r') asfile: data = json.load(file)exceptException: # Too broad!print("Something went wrong")returnNone```## Don't Ignore Exceptions```{python}# BAD - Silent failuretry: result =10/0except:pass# Error is hidden!# GOOD - At least log ittry: result =10/0exceptZeroDivisionErroras e:print(f"Error occurred: {e}") result =None```## Use Finally for Cleanup```{python}import osdef process_file_safely(filename):file=None temp_file ="temp_processing.txt"try:file=open(filename, 'r') content =file.read()# Create temp filewithopen(temp_file, 'w') as tf: tf.write(content.upper())returnTrueexceptExceptionas e:print(f"Error: {e}")returnFalsefinally:# Cleanupiffile:file.close()# Remove temp file if it existsif os.path.exists(temp_file): os.remove(temp_file)print("Temp file cleaned up")```## Provide Context in Error Messages```{python}def divide_list_elements(numbers, divisor): results = []for i, num inenumerate(numbers):try: result = num / divisor results.append(result)exceptZeroDivisionError:# Provide context: which element, what valueprint(f"Error at index {i}: Cannot divide {num} by zero") results.append(None)exceptTypeError:print(f"Error at index {i}: {num} is not a number") results.append(None)return resultsnumbers = [10, 20, "30", 40]results = divide_list_elements(numbers, 0)print(f"Results: {results}")```---## Exercises## Exercise 1: Safe Calculator**Task:** Create a calculator function that:1. Takes two numbers and an operation (+, -, *, /)2. Handles division by zero3. Handles invalid operations4. Uses try-except-else```{python}#| eval: falsedef calculator(num1, num2, operation):# Your code herepass# Test casesprint(calculator(10, 5, '+')) # Should return 15print(calculator(10, 5, '/')) # Should return 2.0print(calculator(10, 0, '/')) # Should handle division by zeroprint(calculator(10, 5, '^')) # Should handle invalid operation```**Solution:**```{python}#| code-fold: true#| code-summary: "Click to show solution"def calculator(num1, num2, operation):try:if operation =='+': result = num1 + num2elif operation =='-': result = num1 - num2elif operation =='*': result = num1 * num2elif operation =='/': result = num1 / num2else:raiseValueError(f"Invalid operation: {operation}")exceptZeroDivisionError:print("Error: Cannot divide by zero")returnNoneexceptValueErroras e:print(f"Error: {e}")returnNoneelse:print(f"Success: {num1}{operation}{num2} = {result}")return result# Test casescalculator(10, 5, '+')calculator(10, 5, '/')calculator(10, 0, '/')calculator(10, 5, '^')```## Exercise 2: File Statistics**Task:** Write a function that:1. Reads a file with numbers (one per line)2. Calculates sum, average, min, max3. Handles file not found4. Handles non-numeric values5. Uses try-except-else-finally```{python}#| eval: falsedef file_statistics(filename):# Your code herepassfile_statistics('data/numbers.txt')```**Solution:**```{python}#| code-fold: true#| code-summary: "Click to show solution"def file_statistics(filename): numbers = [] errors =0try:withopen(filename, 'r') asfile:for line infile: line = line.strip()ifnot line:continuetry: number =float(line) numbers.append(number)exceptValueError: errors +=1exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNoneelse:if numbers: stats = {'count': len(numbers),'sum': sum(numbers),'average': sum(numbers) /len(numbers),'min': min(numbers),'max': max(numbers) }print(f"Successfully processed {len(numbers)} numbers")if errors:print(f"Skipped {errors} invalid entries")return statselse:print("No valid numbers found")returnNonefinally:print("File processing complete")stats = file_statistics('data/numbers.txt')if stats:print("\nStatistics:")for key, value in stats.items():print(f" {key}: {value}")```## Exercise 3: Score Parser**Task:** Create a function that:1. Reads `data/scores.txt` (format: "Name:Score")2. Parses each line into a dictionary3. Handles missing scores (empty after colon)4. Handles invalid score values5. Returns valid scores and lists errors```{python}#| eval: falsedef parse_scores(filename):# Your code herepassscores, errors = parse_scores('data/scores.txt')```**Solution:**```{python}#| code-fold: true#| code-summary: "Click to show solution"def parse_scores(filename): scores = {} errors = []try:withopen(filename, 'r') asfile:for line_num, line inenumerate(file, 1): line = line.strip()ifnot line:continuetry:# Split by colon name, score_str = line.split(':') name = name.strip() score_str = score_str.strip()# Handle empty scoreifnot score_str:raiseValueError("Missing score")# Convert to int score =int(score_str)# Validate score rangeif score <0or score >100:raiseValueError("Score out of range (0-100)") scores[name] = scoreexceptValueErroras e: error_msg =f"Line {line_num} ({line}): {e}" errors.append(error_msg)exceptFileNotFoundError:print(f"Error: File '{filename}' not found")returnNone, Noneelse:print(f"Parsed {len(scores)} valid scores")if errors:print(f"Found {len(errors)} errors")return scores, errorsscores, errors = parse_scores('data/scores.txt')if scores isnotNone:print("\nValid Scores:")for name, score in scores.items():print(f" {name}: {score}")if errors:print("\nErrors:")for error in errors:print(f" - {error}")```## Exercise 4: Robust JSON Loader**Task:** Create a function that:1. Tries to load a JSON file2. If file not found, creates it with default data3. If JSON is invalid, backs up the corrupted file and creates new one4. Returns the loaded or created data5. Uses try-except-else-finally```{python}#| eval: falsedef load_or_create_json(filename, default_data=None):# Your code herepassdata = load_or_create_json('exercises/settings.json', {'theme': 'light', 'lang': 'en'})```**Solution:**```{python}#| code-fold: true#| code-summary: "Click to show solution"import jsonimport osfrom datetime import datetimedef load_or_create_json(filename, default_data=None):if default_data isNone: default_data = {} data =None operation =Nonetry:withopen(filename, 'r') asfile: data = json.load(file) operation ="loaded"exceptFileNotFoundError:print(f"File not found. Creating {filename} with defaults.") data = default_data operation ="created"except json.JSONDecodeError as e:print(f"Invalid JSON in {filename}: {e}")# Backup corrupted file backup_name =f"{filename}.corrupted.{datetime.now().strftime('%Y%m%d_%H%M%S')}"if os.path.exists(filename): os.rename(filename, backup_name)print(f"Corrupted file backed up to: {backup_name}") data = default_data operation ="recreated"else:print(f"Successfully loaded {filename}")finally:# Save data if it was created or recreatedif operation in ["created", "recreated"]:try:withopen(filename, 'w') asfile: json.dump(data, file, indent=2)print(f"Saved {filename}")exceptExceptionas e:print(f"Error saving file: {e}")return data# Test the functiondefault_settings = {'theme': 'light', 'language': 'en', 'notifications': True}data = load_or_create_json('exercises/settings.json', default_settings)print(f"\nData: {json.dumps(data, indent=2)}")```## Exercise 5: Advanced - Data Validator**Task:** Create a comprehensive data validation system:1. Define custom exceptions for different validation errors2. Validate user data (age, email format, username length)3. Collect all validation errors (don't stop at first error)4. Return valid data or raise exception with all errors```{python}#| eval: falseclass ValidationError(Exception):passdef validate_user_data(data):# Your code herepass# Test datatest_users = [ {"username": "alice", "age": 25, "email": "alice@example.com"}, {"username": "ab", "age": -5, "email": "invalid-email"}, {"username": "bob_smith", "age": 30, "email": "bob@example.com"}]```**Solution:**```{python}#| code-fold: true#| code-summary: "Click to show solution"import reclass ValidationError(Exception):"""Custom exception for validation errors"""passclass InvalidAgeError(ValidationError):passclass InvalidEmailError(ValidationError):passclass InvalidUsernameError(ValidationError):passdef validate_user_data(data):""" Validate user data dictionary. Raises ValidationError with all issues found. """ errors = []# Validate usernametry: username = data.get('username', '')iflen(username) <3:raise InvalidUsernameError("Username must be at least 3 characters")iflen(username) >20:raise InvalidUsernameError("Username must be at most 20 characters")ifnot username.replace('_', '').isalnum():raise InvalidUsernameError("Username can only contain letters, numbers, and underscores")except InvalidUsernameError as e: errors.append(f"Username: {e}")# Validate agetry: age = data.get('age')if age isNone:raise InvalidAgeError("Age is required")ifnotisinstance(age, int):raise InvalidAgeError("Age must be an integer")if age <0:raise InvalidAgeError("Age cannot be negative")if age >150:raise InvalidAgeError("Age must be realistic")except InvalidAgeError as e: errors.append(f"Age: {e}")# Validate emailtry: email = data.get('email', '')# Simple email regex email_pattern =r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'ifnot re.match(email_pattern, email):raise InvalidEmailError("Invalid email format")except InvalidEmailError as e: errors.append(f"Email: {e}")# If there are errors, raise exception with all of themif errors: error_message ="Validation failed:\n - "+"\n - ".join(errors)raise ValidationError(error_message)returnTrue# Test with multiple userstest_users = [ {"username": "alice", "age": 25, "email": "alice@example.com"}, {"username": "ab", "age": -5, "email": "invalid-email"}, {"username": "bob_smith", "age": 30, "email": "bob@example.com"}, {"username": "x", "age": 200, "email": "notemail"}]for i, user inenumerate(test_users, 1):print(f"\nValidating user {i}: {user['username']}")try: validate_user_data(user)print(" ✓ Validation passed!")except ValidationError as e:print(f" ✗ {e}")```---# 10. SummaryCongratulations! You've learned comprehensive exception handling in Python.## Key Takeaways1. **Exceptions** are errors that occur during program execution2. **try-except** catches and handles specific exceptions3. **try-except-else** runs code only when no exception occurs4. **try-except-finally** ensures cleanup code always runs5. **Raise** your own exceptions to signal errors6. **Custom exceptions** make your code more maintainable## Exception Handling Cheat Sheet```python# Basic structuretry:# Code that might raise exceptions risky_operation()except SpecificError as e:# Handle specific exception handle_error(e)except (Error1, Error2):# Handle multiple exceptions handle_multiple()exceptExceptionas e:# Catch-all (use sparingly) handle_unknown(e)else:# Runs only if no exception success_code()finally:# Always runs (cleanup) cleanup()# Raising exceptionsraiseValueError("Custom message")raise# Re-raise current exception# Custom exceptionsclass MyCustomError(Exception):pass```## Common Exceptions| Exception | When It Occurs ||-----------|---------------|| `ValueError` | Invalid value for operation || `TypeError` | Wrong type for operation || `ZeroDivisionError` | Division by zero || `FileNotFoundError` | File doesn't exist || `KeyError` | Dictionary key not found || `IndexError` | List index out of range || `AttributeError` | Attribute doesn't exist || `ImportError` | Module can't be imported |## Best Practices Reminder1. Be specific with exception types2. Don't silently ignore exceptions3. Use `finally` for cleanup4. Provide helpful error messages5. Don't catch `Exception` unless necessary6. Use context managers (`with`) when possibleHappy coding!