Exception Handling in Python
Definition: Exception Handling is a mechanism in Python that allows you to gracefully handle runtime errors instead of letting the program crash.Errors are inevitable in programming — a file might not exist, a user might enter invalid input, or a network request might fail.Exception handling ensures your program can respond to these situations intelligently.
---
Errors vs Exceptions
| Type | When It Occurs | Example | Can Be Caught ? |
|---|---|---|---|
| Syntax Error | Before execution(parsing) | print("Hello (missing quote) | ⌠No (fix the code) |
| Exception | During execution (runtime) | 10 / 0 (ZeroDivisionError) | ✅ Yes (try/except) |
---
Common Python Exceptions
| Exception | Cause | Example |
|---|---|---|
ZeroDivisionError | Division by zero | 10 / 0 |
TypeError | Wrong type operation | "hello" + 5 |
ValueError | Correct type, wrong value | int("abc") |
IndexError | Index out of range | lst[100] on a small list |
KeyError | Key not found in dictionary | d["nonexistent_key"] |
FileNotFoundError | File doesn't exist | open("missing.txt") |
ImportError | Module not found | import nonexistent_module |
AttributeError | Object has no attribute | "hello".push("x") |
NameError | Variable not defined | print(undefined_var) |
StopIteration | Iterator exhausted | next() on empty iterator |
---
The try-except Block
Syntax:
try:
# Code that might cause an error
except ExceptionType:
# Code to handle the error
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Output: Cannot divide by zero!
---
Handling Multiple Exceptions
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
---
The else and finally Clauses
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully!") # Runs only if NO exception
print(content)
finally:
print("Cleanup complete.") # ALWAYS runs
Purpose of Each Block:
| Block | When It Runs | Use Case |
|---|---|---|
try | Always (first attempt) | Code that might fail |
except | Only if an exception occurs | Handle the specific error |
else | Only if NO exception occurs | Success logic |
finally | ALWAYS (even if exception occurs) | Cleanup (close files, connections) |
---
Raising Exceptions
You can deliberately raise exceptions using the raise keyword.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
if age > 150:
raise ValueError("Age seems unrealistic!")
return age
try:
set_age(-5)
except ValueError as e:
print(e) # Age cannot be negative!
---
Custom Exceptions
You can create your own exception classes by inheriting from the Exception class.
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Cannot withdraw {amount}. Balance: {balance}")
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance
# Usage
try:
account = BankAccount(1000)
account.withdraw(1500)
except InsufficientFundsError as e:
print(e) # Cannot withdraw 1500. Balance: 1000
---
Exception Handling in Data Science
| Scenario | Exception | How to Handle |
|---|---|---|
| Missing CSV file | FileNotFoundError | Prompt user for correct path |
| Invalid user input for model | ValueError | Validate input before processing |
| API request failure | ConnectionError | Retry with backoff |
| Division by zero in calculations | ZeroDivisionError | Add a check or use try/except |
| Missing dictionary key | KeyError | Use .get(key, default) instead |
| Out-of-memory with large data | MemoryError | Use chunked processing (chunksize in Pandas) |
---
Best Practices
| Practice | Description |
|---|---|
| Be Specific | Catch specific exceptions, not bare except: |
| Don't Suppress | Don't use empty except: pass — at least log the error |
| Use finally | For cleanup operations (closing files, connections) |
| Validate First | Prefer validation over exception handling when possible |
| Custom Exceptions | Create meaningful exception classes for domain-specific errors |
| Log Errors | Use the logging module to record errors for debugging |
Summary
- Exceptions are runtime errors that can be caught and handled gracefully.
try/except/else/finallyprovides a structured way to handle errors.- Common exceptions include
ValueError,TypeError,KeyError, andFileNotFoundError. raiseis used to deliberately trigger exceptions.- Custom exceptions make error handling more meaningful and domain-specific.
- In data science, exception handling is crucial for robust data pipelines and model training.