Exception Handling in Python
Exception Handling is used to handle runtime errors gracefully without crashing the program. Instead of stopping execution, Python allows us to catch errors and handle them properly.
What is an Exception?
An Exception is an error that occurs during program execution.
Example:
print(10 / 0) # ZeroDivisionError
# otput:
# ZeroDivisionError: division by zero- Python stops the program because the error is not handled.
Why Exception Handling is Important?
- Prevents program crash
- Improves user experience
- Helps debugging
- Maintains program flow
- Makes code professional
Syntax:
try:
# Code that may cause error
except:
# Code that runs if error occursExample:
try:
num = int(input("Enter number: "))
print(10 / num)
except:
print("Error occurred!")- If user enters
0or invalid input, program won’t crash.
How try-except Works:
- Python executes code inside try
- If error occurs → jumps to except
- If no error → except block is skipped
Handling Specific Exceptions
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")- Always catch specific exceptions, not generic ones.
Common Built-in Exceptions
Using “as” to Get Error Message
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", e)except ZeroDivisionError as e
- Python catches the error.
- The error object is stored in variable e.
- e contains the message: “division by zero”
Why Use "as e”?
Using as e allows you to:
- Access the exact error message
- Log the error
- Debug efficiently
- Show user-friendly error messages
- Inspect error details
else Block
else runs only if no exception occurs.
try:
num = int(input("Enter number: "))
except ValueError:
print("Invalid input")
else:
print("You entered:", num)finally Block
finally always runs (error or no error).
Used for:
- Closing files
- Closing database connections
- Cleaning resources
try:
f = open("data.txt")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")Full Structure
try:
# risky code
except ExceptionType1:
# handle error
except ExceptionType2:
# handle error
else:
# runs if no error
finally:
# always runsRaising Exceptions (raise)
You can manually create exceptions.
age = int(input("Enter age: "))
if age < 18:
raise ValueError("Age must be 18 or above")
print("Eligible")Creating Custom Exception
class InvalidAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 18:
raise InvalidAgeError("Too young!")Using Exception Class
try:
print(10 / 0)
except Exception as e:
print("Something went wrong:", e)Exceptionis the base class of all exceptions.
Nested try-except
try:
try:
print(10 / 0)
except ZeroDivisionError:
print("Inner handled")
except:
print("Outer handled")Best Practices
- Catch specific exceptions
- Avoid empty except block
- Use finally for cleanup
- Don’t overuse try-except
- Log errors in real projects
Real-World Example
try:
with open("data.txt", "r") as f:
data = f.read()
except FileNotFoundError:
print("File does not exist")
except PermissionError:
print("No permission to read file")
else:
print("File content loaded successfully")
finally:
print("Operation finished")Logging Exceptions
In real-world applications, we don’t just print errors — we log them.
Get Saurabh Gandhi’s stories in your inbox
Join Medium for free to get updates from this writer.
Python provides the built-in module: logging
Why Use Logging Instead of print()?
Basic Logging Example
import logging
logging.basicConfig(
filename="app.log",
level=logging.ERROR,
format="%(asctime)s - %(levelname)s - %(message)s"
)
try:
10 / 0
except ZeroDivisionError as e:
logging.error("Division failed", exc_info=True)What Happens?
- Error stored in app.log
- Stack trace saved
- Program continues safely
Logging Levels
logging.debug("Debug info")
logging.info("Information")
logging.warning("Warning message")
logging.error("Error occurred")
logging.critical("Critical issue")Custom Exception Hierarchy
In large systems, we don’t use generic ValueError.
We create our own structured exception system.
Example : E-commerce Application
class AppError(Exception):
"""Base class for all application errors"""
pass
class DatabaseError(AppError):
pass
class PaymentError(AppError):
pass
class ValidationError(AppError):
passUsage
def process_payment(amount):
if amount <= 0:
raise ValidationError("Invalid payment amount")
raise PaymentError("Payment gateway not responding")
try:
process_payment(-10)
except ValidationError as e:
print("Validation failed:", e)
except PaymentError as e:
print("Payment issue:", e)
except AppError as e:
print("General app error:", e)Why Custom Hierarchy?
- Centralized error management
- Cleaner architecture
- Easier debugging
- Enterprise-ready structure
Exception Chaining
Sometimes one exception occurs because of another exception.
Python supports chaining using:
raise NewException() from original_exceptionExample Without Chaining
try:
int("abc")
except ValueError:
raise TypeError("Conversion failed")- You lose the original error cause
Example With Chaining
try:
int("abc")
except ValueError as e:
raise TypeError("Conversion failed") from eOutput shows:
- Original ValueError
- New TypeError
- Full traceback chain
This is extremely useful in large systems.
Questions
- What is the difference between error and exception?
- What is the difference between except and finally?
- Why should we avoid bare except?
- What happens if an exception is not handled?
- Difference between raise and assert?
- Can we have multiple except blocks?
- What is the base class of all exceptions?
- When does else block execute?
- What is exception chaining?
- Difference between raise and raise from?
- Why use custom exception hierarchy?
- How does logging improve debugging?
- When should we re-raise exceptions?








