🚨 Handling Exceptions
Exception handling with try/except blocks is the foundation of error management in Python. It allows your program to continue running even when errors occur, providing graceful error recovery.
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
result = 0
print(f"Result: {result}")
🎯 Basic Exception Handling
The try/except statement catches and handles exceptions.
Simple Exception Handling
# Handle division by zero
try:
number = 10 / 0
except ZeroDivisionError:
print("Division by zero error")
number = 0
# Handle invalid conversion
try:
age = int("abc")
except ValueError:
print("Invalid number format")
age = 0
# Handle missing dictionary key
data = {"name": "Alice"}
try:
email = data["email"]
except KeyError:
print("Email key not found")
email = "unknown"
print(f"Number: {number}, Age: {age}, Email: {email}")
Getting Exception Information
# Capture exception details
try:
result = int("invalid")
except ValueError as e:
print(f"Error occurred: {e}")
print(f"Error type: {type(e).__name__}")
# Multiple ways to get error info
try:
missing_file = open("nonexistent.txt")
except FileNotFoundError as error:
print(f"File error: {error}")
print(f"Error args: {error.args}")
🔄 Multiple Exception Handling
Handle different types of exceptions with multiple except blocks.
Multiple Except Blocks
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero")
return 0
except TypeError:
print("Invalid data types for division")
return None
# Test different scenarios
print(safe_divide(10, 2)) # Normal division
print(safe_divide(10, 0)) # Division by zero
print(safe_divide("10", 2)) # Type error
Catching Multiple Exception Types
# Handle multiple exceptions in one block
try:
data = {"count": "5"}
result = 10 / int(data["count"])
except (ValueError, TypeError, KeyError) as e:
print(f"Data processing error: {e}")
result = 0
# Handle any exception
try:
risky_operation = 1 / 0
except Exception as e:
print(f"Unexpected error: {e}")
risky_operation = None
print(f"Result: {result}")
Exception Hierarchy
# Catch specific first, then general
try:
numbers = [1, 2, 3]
value = numbers[10]
except IndexError:
print("Index out of range")
value = 0
except Exception as e:
print(f"Other error: {e}")
value = None
print(f"Value: {value}")
📋 Essential Exception Handling Patterns
Pattern | Syntax | Use Case |
---|---|---|
Basic | except ValueError: | Handle specific exception |
With info | except ValueError as e: | Get exception details |
Multiple types | except (ValueError, TypeError): | Handle several exceptions |
Catch all | except Exception: | Handle any exception |
Bare except | except: | Handle everything (not recommended) |
🔧 Finally and Else Blocks
Finally Block
# Finally always executes
file = None
try:
file = open("data.txt", "w")
file.write("test data")
except IOError:
print("File operation failed")
finally:
if file:
file.close()
print("File closed")
Else Block
# Else runs if no exceptions occur
def safe_conversion(value):
try:
number = int(value)
except ValueError:
print("Conversion failed")
return None
else:
print("Conversion successful")
return number
finally:
print("Conversion attempt completed")
result1 = safe_conversion("42")
result2 = safe_conversion("abc")
Complete Exception Structure
def process_data(data):
try:
# Try to process the data
processed = data.upper().strip()
length = len(processed)
except AttributeError:
print("Data is not a string")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
else:
print("Processing successful")
return processed
finally:
print("Processing attempt finished")
# Test the function
result1 = process_data(" hello world ")
result2 = process_data(123)
📊 Exception Handling Reference
Common Exception Types
Exception | Cause | Example Code |
---|---|---|
ValueError | Invalid value | int("abc") |
TypeError | Wrong type | "text" + 5 |
KeyError | Missing dict key | d["missing"] |
IndexError | Invalid index | list[100] |
AttributeError | Missing attribute | obj.missing() |
FileNotFoundError | Missing file | open("missing.txt") |
ZeroDivisionError | Division by zero | 10 / 0 |
Exception Handling Best Practices
Practice | Good Example | Avoid |
---|---|---|
Specific exceptions | except ValueError: | except: |
Meaningful messages | print("Invalid input") | print("Error") |
Handle what you expect | except FileNotFoundError: | except Exception: |
Use finally for cleanup | finally: file.close() | Ignoring cleanup |
🎯 Key Takeaways
🚀 What's Next?
Learn how to create your own custom exception classes for specific error scenarios.
Continue to: Create Custom Exceptions
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.