try-except Exception Handling
Handling Errors Gracefully
Basic Syntax
python
try:
# Code that might error
risky_operation()
except ExceptionType:
# Handle the error
handle_error()Basic Usage
Example 1: Catching Specific Exceptions
python
try:
age = int(input("Please enter age: "))
print(f"Your age is {age}")
except ValueError:
print(" Please enter a valid number")Example 2: Catching Multiple Exceptions
python
try:
income = int(input("Income: "))
tax = income / 0.25
except ValueError:
print(" Income must be a number")
except ZeroDivisionError:
print(" Divisor cannot be zero")Example 3: Catching All Exceptions
python
try:
# Risky operation
result = risky_function()
except Exception as e:
print(f" Error occurred: {e}")Complete Syntax
try-except-else-finally
python
try:
# Code to attempt
result = 10 / 2
except ZeroDivisionError:
# Execute when error occurs
print(" Division by zero")
else:
# Execute when no error
print(f" Result: {result}")
finally:
# Always executes (cleanup resources)
print("Calculation complete")Real-World Cases
Case 1: Safe Data Loading
python
import pandas as pd
from pathlib import Path
def load_survey_data(filename):
"""Safely load survey data"""
try:
if not Path(filename).exists():
raise FileNotFoundError(f"File doesn't exist: {filename}")
df = pd.read_csv(filename)
# Validate required columns
required_cols = ['id', 'age', 'income']
missing_cols = set(required_cols) - set(df.columns)
if missing_cols:
raise ValueError(f"Missing columns: {missing_cols}")
return df
except FileNotFoundError as e:
print(f" File error: {e}")
return None
except pd.errors.EmptyDataError:
print(" File is empty")
return None
except Exception as e:
print(f" Unknown error: {e}")
return None
# Usage
df = load_survey_data('survey.csv')
if df is not None:
print(f" Successfully loaded {len(df)} rows")Case 2: Batch Data Processing
python
# Survey data (may have errors)
responses = [
{'id': 1, 'age': '25', 'income': '50000'},
{'id': 2, 'age': 'N/A', 'income': '75000'},
{'id': 3, 'age': '35', 'income': 'unknown'},
{'id': 4, 'age': '40', 'income': '85000'}
]
valid_data = []
errors = []
for resp in responses:
try:
# Attempt conversion
clean_resp = {
'id': resp['id'],
'age': int(resp['age']),
'income': float(resp['income'])
}
valid_data.append(clean_resp)
except (ValueError, KeyError) as e:
errors.append({
'id': resp.get('id', 'unknown'),
'error': str(e)
})
print(f" Valid data: {len(valid_data)} records")
print(f" Errors: {len(errors)} records")
for error in errors:
print(f" ID {error['id']}: {error['error']}")Case 3: API Request Retry
python
import requests
import time
def fetch_data(url, max_retries=3):
"""API request with retry"""
for attempt in range(max_retries):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Check HTTP errors
return response.json()
except requests.exceptions.Timeout:
print(f"⏱️ Timeout, retry {attempt + 1}/{max_retries}")
time.sleep(2 ** attempt) # Exponential backoff
except requests.exceptions.HTTPError as e:
print(f" HTTP error: {e}")
return None
except requests.exceptions.RequestException as e:
print(f" Request error: {e}")
return None
print(f" Maximum retries reached")
return NoneBest Practices
1. Catch Specific Exceptions
python
# Too broad
try:
result = risky_operation()
except:
print("Error occurred")
# Specific and clear
try:
result = risky_operation()
except ValueError:
print("Value error")
except FileNotFoundError:
print("File doesn't exist")2. Use else Clause
python
try:
df = pd.read_csv('data.csv')
except FileNotFoundError:
print(" File doesn't exist")
else:
# Only executes on success
print(f" Loaded {len(df)} rows")
df.to_stata('output.dta')3. finally for Cleanup
python
file = None
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print(" File doesn't exist")
finally:
# Ensure file is closed
if file:
file.close()
# Better way: Use with
with open('data.txt', 'r') as file:
content = file.read() # Auto-closes4. Log Errors
python
import logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
try:
result = risky_operation()
except Exception as e:
logging.error(f"Error: {e}", exc_info=True)
print(" Error occurred, see log")Custom Exceptions
python
class InvalidAgeError(Exception):
"""Invalid age exception"""
pass
def validate_respondent(age, income):
"""Validate respondent data"""
if age < 18 or age > 100:
raise InvalidAgeError(f"Invalid age: {age}")
if income < 0:
raise ValueError(f"Income cannot be negative: {income}")
# Usage
try:
validate_respondent(age=150, income=50000)
except InvalidAgeError as e:
print(f" {e}")
except ValueError as e:
print(f" {e}")When to Use try-except?
Suitable Scenarios
- File operations (file may not exist)
- Network requests (may timeout)
- User input (may be invalid)
- Data conversions (may fail)
Unsuitable Scenarios
python
# Don't use exceptions to replace normal logic
try:
value = dict['key']
except KeyError:
value = None
# Use conditional logic
value = dict.get('key', None)Practice Questions
python
# Exercise 1: Safe mean calculation
def safe_mean(data):
"""Calculate mean, handle empty list and non-numbers"""
try:
# Your code
pass
except:
return None
# Exercise 2: Batch file processing
# Read all CSV files in a folder
# For each file:
# - try to read
# - except record error
# - If successful, add to listNext Steps
Next section learns Debugging Tips.
Continue!