
Python
Learn what exceptions are, how they occur, and why proper error handling prevents your programs from crashing unexpectedly.
An exception is an unexpected event during program execution that disrupts normal flow. When Python encounters an error, it raises (throws) an exception.
Without proper handling, exceptions crash your program. With handling, you can respond gracefully.
# Without error handling - CRASHES!
file = open("nonexistent.txt")
content = file.read()
print("File loaded successfully") # Never reaches here
# Output: FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'# With error handling - SURVIVES!
try:
file = open("nonexistent.txt")
content = file.read()
except FileNotFoundError:
print("File not found! Using default content instead.")
print("Program continues...") # This runs regardlessPython provides exceptions for common problems. Here are the most important:
# ZeroDivisionError - dividing by zero
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# ValueError - wrong value type
try:
age = int("twenty") # Can't convert "twenty" to int
except ValueError:
print("Age must be a number!")
# IndexError - accessing invalid list position
try:
fruits = ["apple", "banana"]
print(fruits[5]) # Only 2 items, index 5 doesn't exist
except IndexError:
print("That fruit doesn't exist in our list!")
# KeyError - accessing missing dictionary key
try:
user = {"name": "Alice", "age": 30}
print(user["email"]) # Key "email" doesn't exist
except KeyError:
print("Email not found in user data!")
# TypeError - wrong data type
try:
text = "hello"
result = text + 5 # Can't add string and integer
except TypeError:
print("Cannot add string and number!")Python organizes exceptions in a hierarchy. All exceptions inherit from `BaseException`:
# Viewing the exception hierarchy
import sys
# Print exception info when it occurs
try:
items = [1, 2, 3]
print(items[10])
except IndexError as e:
print(f"Exception type: {type(e).__name__}")
print(f"Exception message: {e}")
print(f"Base classes: {type(e).__bases__}")
# Output:
# Exception type: IndexError
# Exception message: list index out of range
# Base classes: (<class 'LookupError'>,)Common exception parents:
# 1. Invalid operations
result = 100 / 0 # ZeroDivisionError
# 2. Type mismatches
count = "5" + 10 # TypeError
# 3. Missing data
data = {}
value = data["missing_key"] # KeyError
# 4. File issues
file = open("/path/that/doesnt/exist.txt") # FileNotFoundError
# 5. Network problems
import requests
response = requests.get("invalid_url") # ConnectionError
# 6. API/Resource issues
import json
data = json.loads("not valid json") # JSONDecodeError
# 7. Attribute access
class Person:
def __init__(self, name):
self.name = name
person = Person("Alice")
print(person.age) # AttributeError: no attribute 'age'# Scenario: Processing user data from API
import json
# WITHOUT error handling - fragile
def process_user_data(json_string):
data = json.loads(json_string) # Crashes if invalid JSON
age = int(data["age"]) # Crashes if "age" missing
return age * 2
# Call with bad data crashes the entire program
# process_user_data("not json") # JSONDecodeError!
# process_user_data('{"name": "Alice"}') # KeyError!
# WITH error handling - robust
def process_user_data_safe(json_string):
try:
data = json.loads(json_string)
age = int(data["age"])
return age * 2
except json.JSONDecodeError:
print("Invalid JSON format. Using default age.")
return 50
except KeyError:
print("Age field missing. Using default age.")
return 50
except ValueError:
print("Age must be a number. Using default age.")
return 50
# Handles bad data gracefully
print(process_user_data_safe("not json")) # Uses default
print(process_user_data_safe('{"name": "Alice"}')) # Uses default
print(process_user_data_safe('{"age": "30"}')) # Returns 60Every exception has important information:
try:
numbers = [1, 2, 3]
print(numbers[5])
except IndexError as error:
print(f"Type: {type(error).__name__}")
print(f"Message: {error}")
print(f"Args: {error.args}")
# Output:
# Type: IndexError
# Message: list index out of range
# Args: ('list index out of range',)Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward