🛡️ What is Exception Handling in Python?
An exception is a runtime error that disrupts normal program execution (e.g., dividing by zero, accessing missing files, or incorrect data types). Instead of letting the application crash, Python provides structured exception handling blocks:
• try: Tests a block of code for errors.
• except: Handles specific errors gracefully.
• else: Executes code if no exceptions occurred.
• finally: Always executes for clean-up tasks (closing files, releasing database connections).
1. Basic Try-Except Block (ZeroDivisionError)
Catch division-by-zero errors gracefully without crashing the running script.
Python
try:
result = 100 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
print("Program continues executing normally after exception handling.")
Output:
Error: Division by zero is not allowed.
Program continues executing normally after exception handling.
Real-Time Example 1: Catching Multiple Exception Types
Handle different runtime errors (like ValueError and ZeroDivisionError) with dedicated except blocks.
Python
def safe_divide(a, b):
try:
num1 = float(a)
num2 = float(b)
result = num1 / num2
print(f"Division Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid numeric input provided.")
safe_divide(50, "abc")
safe_divide(50, 0)
safe_divide(50, 5)
Output:
Error: Invalid numeric input provided.
Error: Cannot divide by zero.
Division Result: 10.0
Real-Time Example 2: The Else Block (Successful Execution)
Use the
else block to run code only when the try block completes without raising any exceptions.
Python
def parse_user_age(age_str):
try:
age = int(age_str)
except ValueError:
print("Exception: Please enter a valid integer age.")
else:
print(f"Success! Parsed age: {age}")
parse_user_age("twenty-five") # Triggers except
parse_user_age("25") # Triggers else
Output:
Exception: Please enter a valid integer age.
Success! Parsed age: 25
Real-Time Example 3: The Finally Block (Guaranteed Cleanup)
The
finally block always executes, regardless of whether an exception occurred or was handled. Perfect for resource cleanup.
Python
def simulate_database_query():
print("1. Opening database connection...")
try:
# Simulate an error during query execution
raise ConnectionError("Database timeout error!")
except ConnectionError as e:
print(f"2. Caught Exception: {e}")
finally:
print("3. Cleanup: Closing database connection securely.")
simulate_database_query()
Output:
1. Opening database connection...
2. Caught Exception: Database timeout error!
3. Cleanup: Closing database connection securely.
Real-Time Example 4: File Handling Safety with Try-Finally
Ensure files are closed properly using
finally even if file reading fails.
Python
file = None
try:
file = open("report.txt", "r")
print(file.read())
except FileNotFoundError:
print("Error: Report file missing on disk.")
finally:
if file:
file.close()
print("File stream closed successfully in finally block.")
Output:
Error: Report file missing on disk.
File stream closed successfully in finally block.
Real-Time Example 5: Raising Custom Exceptions (raise keyword)
Trigger custom runtime exceptions manually using the
raise statement when business rules are violated.
Python
def withdraw_funds(balance, amount):
if amount > balance:
raise ValueError("Insufficient balance for withdrawal.")
return balance - amount
try:
new_bal = withdraw_funds(5000, 8000)
except ValueError as e:
print("Transaction Failed:", e)
Output:
Transaction Failed: Insufficient balance for withdrawal.
Real-Time Example 6: Defining Custom Exception Classes
Create custom exception classes by inheriting from Python's built-in
Exception class.
Python
class InsufficientStockError(Exception):
"""Custom exception for inventory stock depletion."""
pass
def fulfill_order(stock, requested):
if requested > stock:
raise InsufficientStockError(f"Requested {requested} units, but only {stock} available.")
return "Order fulfilled successfully."
try:
print(fulfill_order(10, 25))
except InsufficientStockError as e:
print("Inventory Alert:", e)
Output:
Inventory Alert: Requested 25 units, but only 10 available.
Real-Time Example 7: Catching Exception Details (as e)
Capture exception object details using the
as e syntax to inspect system error messages.
Python
try:
number = int("NotANumber")
except ValueError as e:
print("Captured Error Details:", type(e).__name__, "->", e)
Output:
Captured Error Details: ValueError -> invalid literal for int() with base 10: 'NotANumber'
Real-Time Example 8: User Input Validation Loop
Keep prompting users for correct numeric input using a
while loop combined with try-except validation.
Python
# Simulating user input validation sequence
simulated_inputs = ["abc", "-5", "42"]
input_idx = 0
valid_age = None
while valid_age is None:
current_input = simulated_inputs[input_idx]
input_idx += 1
try:
val = int(current_input)
if val <= 0:
raise ValueError("Age must be positive.")
valid_age = val
print(f"Accepted valid age: {valid_age}")
except ValueError as err:
print(f"Input '{current_input}' rejected: {err}")
Output:
Input 'abc' rejected: invalid literal for int() with base 10: 'abc'
Input '-5' rejected: Age must be positive.
Accepted valid age: 42
Real-Time Example 9: API Request Error Handling Simulation
Simulate robust API call error handling catching connection timeouts and parsing errors.
Python
def fetch_api_data(status_code):
try:
if status_code == 500:
raise ConnectionError("Server Internal Error 500.")
elif status_code == 404:
raise LookupError("Resource Not Found 404.")
print("API Response parsed successfully.")
except (ConnectionError, LookupError) as e:
print("API Request Failed:", e)
finally:
print("API session metrics logged.")
fetch_api_data(500)
Output:
API Request Failed: Server Internal Error 500.
API session metrics logged.