Master Python exception handling with try-except-else-finally blocks. Learn best practices, custom exceptions, and error handling patterns.
📌 Python exception handling, try except, Python errors, custom exceptions, finally block, else clause
Exception handling is your reliable protector against chaos in code. It prevents crashes and makes programs more robust by gracefully managing errors that would otherwise terminate your application.
Exceptions are events that disrupt normal program execution—like dividing by zero, accessing missing files, or converting invalid strings to numbers. Python's try-except mechanism intercepts these disruptions before they crash your program.
The basic try-except structure wraps risky code in a try block and specifies exception types to catch in except blocks. This separates error handling logic from normal business logic, making code cleaner and more maintainable.
Python's complete exception handling structure includes four components: try (risky code), except (error handlers), else (success-only code), and finally (cleanup that always runs). Understanding when each executes is crucial for robust error handling.
The else clause executes only when no exception occurs—perfect for success-dependent code. The finally block always executes regardless of exceptions, making it ideal for cleanup operations like closing files or database connections.
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: division by zero!")
result = None
# Prevents crash, handles error gracefullytry:
file_name = input("Enter file name: ")
file = open(file_name, "r")
line = file.readline()
number = int(line.strip())
result = 100 / number
except FileNotFoundError:
print(f"File {file_name} not found")
except ValueError:
print("Cannot convert data to a number")
except ZeroDivisionError:
print("Error: division by zero")try:
number = int("42")
except ValueError:
print("This is not a number")
else:
# Only runs if no exception
print(f"Success! Number: {number}")
print(f"Square: {number ** 2}")
finally:
# Always runs for cleanup
print("Operation completed")class InvalidEmailError(Exception):
"""Raised when an email doesn't match the format"""
pass
def validate_email(email):
if "@" not in email:
raise InvalidEmailError("Email must contain @ symbol")
print(f"Email {email} is valid")
# Usage
try:
validate_email("invalid.email")
except InvalidEmailError as e:
print(f"Validation failed: {e}")def read_config(filename):
config = {}
file = None
try:
file = open(filename, 'r')
for line in file:
key, value = line.strip().split('=')
config[key] = value
except FileNotFoundError:
print(f"Config file {filename} not found, using defaults")
config = {"theme": "dark", "language": "en"}
except ValueError:
print("Invalid config format")
finally:
if file:
file.close() # Always cleanup
return config