What is Exception Handling?
Exception handling allows a Python program to handle unexpected
situations without terminating the entire application.
Python uses try, except,
else, and finally blocks to manage
exceptions.
Contains code that might generate an exception.
Handles an exception when one occurs.
Runs when no exception occurs.
Runs whether an exception occurs or not.
The simplest way to handle an exception is to place
potentially risky code inside a try block and
handle the error in an except block.
try:
number = 10 / 0
print(number)
except:
print("An error occurred.")
An error occurred.
Dividing a number by zero raises
ZeroDivisionError.
try:
amount = 1000
people = 0
share = amount / people
except ZeroDivisionError:
print("Number of people cannot be zero.")
Number of people cannot be zero.
ValueError occurs when a function receives a
value of the correct type but an inappropriate value.
try:
age = int("twenty")
print(age)
except ValueError:
print("Please enter a valid number.")
Please enter a valid number.
TypeError occurs when an operation is
performed on incompatible data types.
try:
result = "100" + 50
print(result)
except TypeError:
print("Cannot add a string and an integer.")
Cannot add a string and an integer.
IndexError occurs when you try to access a
list or sequence position that does not exist.
try:
students = ["Rahul", "Priya", "Amit"]
print(students[5])
except IndexError:
print("Student position does not exist.")
Student position does not exist.
KeyError occurs when a dictionary key does
not exist.
try:
employee = {
"name": "Rahul",
"department": "IT"
}
print(employee["salary"])
except KeyError:
print("Salary information is not available.")
Salary information is not available.
When a program attempts to read a file that does not exist,
Python raises FileNotFoundError.
try:
with open("customers.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Customer file was not found.")
Customer file was not found.
A program can have multiple except blocks to
handle different types of exceptions separately.
try:
number = int(input("Enter a number: "))
result = 100 / number
print("Result:", result)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Number cannot be zero.")
Please enter a valid integer.
The else block runs only when the
try block completes successfully.
try:
number = int("100")
except ValueError:
print("Invalid number.")
else:
print("Number converted successfully.")
print("Value:", number)
Number converted successfully.
Value: 100
The finally block executes whether an
exception occurs or not. It is commonly used for cleanup.
try:
number = 10 / 2
print(number)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Operation completed.")
5.0
Operation completed.
An ATM application can use exception handling to validate withdrawal requests and prevent unexpected failures.
balance = 10000
try:
amount = int(input("Enter withdrawal amount: "))
if amount <= 0:
raise ValueError("Amount must be greater than zero.")
if amount > balance:
raise ValueError("Insufficient balance.")
balance -= amount
except ValueError as error:
print("Transaction failed:", error)
else:
print("Withdrawal successful.")
print("Remaining balance:", balance)
finally:
print("Thank you for using the ATM.")
Enter withdrawal amount: 12000
Transaction failed: Insufficient balance.
Thank you for using the ATM.
A login system can handle missing data and invalid input without crashing the application.
users = {
"rahul": "python123",
"priya": "admin456"
}
try:
username = input("Username: ")
password = input("Password: ")
if username not in users:
raise KeyError("User does not exist.")
if users[username] != password:
raise ValueError("Incorrect password.")
except KeyError as error:
print("Login failed:", error)
except ValueError as error:
print("Login failed:", error)
else:
print("Login successful.")
Username: rahul
Password: wrong123
Login failed: Incorrect password.
An e-commerce application can use exception handling when calculating prices from user or external data.
try:
price = float(input("Enter product price: "))
quantity = int(input("Enter quantity: "))
if price < 0 or quantity < 0:
raise ValueError("Price and quantity cannot be negative.")
total = price * quantity
except ValueError as error:
print("Invalid order:", error)
else:
print("Total price: โน", total)
Enter product price: 500
Enter quantity: 3
Total price: โน 1500.0
The raise statement allows a program to
intentionally generate an exception when a business rule
is violated.
age = 15
try:
if age < 18:
raise ValueError("Customer must be at least 18 years old.")
print("Registration allowed.")
except ValueError as error:
print("Registration failed:", error)
Registration failed: Customer must be at least 18 years old.
You can store the exception object in a variable using
as and display its message.
try:
result = 10 / 0
except ZeroDivisionError as error:
print("Error:", error)
Error: division by zero
Related exceptions can be handled by passing them as a
tuple to a single except block.
try:
value = int(input("Enter a number: "))
result = 100 / value
except (ValueError, ZeroDivisionError):
print("Please enter a valid non-zero number.")
Please enter a valid non-zero number.
You can create your own exception class when an application needs a meaningful domain-specific error.
class InsufficientBalanceError(Exception):
pass
balance = 5000
withdrawal = 7000
try:
if withdrawal > balance:
raise InsufficientBalanceError(
"Insufficient account balance."
)
balance -= withdrawal
except InsufficientBalanceError as error:
print("Transaction failed:", error)
Transaction failed: Insufficient account balance.
A bank account can use a custom exception to prevent a withdrawal from exceeding the available balance.
class InsufficientBalanceError(Exception):
pass
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount <= 0:
raise ValueError(
"Withdrawal must be greater than zero."
)
if amount > self.balance:
raise InsufficientBalanceError(
"Insufficient balance."
)
self.balance -= amount
return self.balance
account = BankAccount(10000)
try:
remaining = account.withdraw(3000)
except (ValueError, InsufficientBalanceError) as error:
print("Transaction failed:", error)
else:
print("Withdrawal successful.")
print("Remaining balance:", remaining)
Withdrawal successful.
Remaining balance: 7000
Exception handling is useful when applications read configuration files, reports, customer records, or logs.
try:
with open("employees.txt", "r") as file:
data = file.read()
except FileNotFoundError:
print("Employee file does not exist.")
except PermissionError:
print("You do not have permission to read the file.")
else:
print("Employee data loaded successfully.")
print(data)
finally:
print("File processing completed.")
Employee data loaded successfully.
Employee records...
File processing completed.
Functions can contain exception handling so that callers receive a safe result instead of an unexpected crash.
def calculate_average(total, count):
try:
return total / count
except ZeroDivisionError:
return 0
print(calculate_average(500, 5))
print(calculate_average(500, 0))
100.0
0
| Exception | When It Occurs | Real-Time Example |
|---|---|---|
ValueError |
Invalid value | Invalid age or price input |
TypeError |
Incompatible data types | Adding string and number |
ZeroDivisionError |
Division by zero | Financial calculation |
IndexError |
Invalid sequence index | Accessing missing list item |
KeyError |
Missing dictionary key | Missing employee field |
FileNotFoundError |
File does not exist | Reading a missing report |
PermissionError |
Insufficient file permission | Opening a protected file |
This example combines input validation, custom exceptions,
try, except, else,
and finally in a small order-processing
application.
class InvalidOrderError(Exception):
pass
def place_order(product, price, quantity):
try:
if not product:
raise InvalidOrderError(
"Product name is required."
)
if price <= 0:
raise InvalidOrderError(
"Price must be greater than zero."
)
if quantity <= 0:
raise InvalidOrderError(
"Quantity must be greater than zero."
)
total = price * quantity
except InvalidOrderError as error:
print("Order failed:", error)
else:
print("Order placed successfully.")
print("Product:", product)
print("Quantity:", quantity)
print("Total: โน", total)
finally:
print("Order processing completed.")
place_order("Laptop", 55000, 2)
Order placed successfully.
Product: Laptop
Quantity: 2
Total: โน 110000
Order processing completed.
Prefer except ValueError over a
completely generic except.
Put only the code that may fail inside the
try block.
Use finally for operations that must
happen regardless of success or failure.
Use raise when application rules are
violated.
Use custom exception classes for meaningful application-specific errors.
Do not hide errors without providing useful handling or logging.
Contains code that may raise an exception.
Handles one or more exceptions.
Executes only when the try block
succeeds.
Executes whether an exception occurs or not.
Manually raises an exception.
Creates application-specific error types.