PYTHON EXCEPTION HANDLING

Learn how Python detects, handles, and recovers from runtime errors using practical real-time examples.

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.

๐Ÿงช try

Contains code that might generate an exception.

๐Ÿ›ก๏ธ except

Handles an exception when one occurs.

โœ… else

Runs when no exception occurs.

๐Ÿ”’ finally

Runs whether an exception occurs or not.

try
โ†’
except
โ†’
Program Continues
1. Basic try-except

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.

Python
try:
    number = 10 / 0
    print(number)

except:
    print("An error occurred.")
Output:
An error occurred.
2. Handling ZeroDivisionError

Dividing a number by zero raises ZeroDivisionError.

Python
try:
    amount = 1000
    people = 0

    share = amount / people

except ZeroDivisionError:
    print("Number of people cannot be zero.")
Output:
Number of people cannot be zero.
3. Handling ValueError

ValueError occurs when a function receives a value of the correct type but an inappropriate value.

Python
try:
    age = int("twenty")
    print(age)

except ValueError:
    print("Please enter a valid number.")
Output:
Please enter a valid number.
4. Handling TypeError

TypeError occurs when an operation is performed on incompatible data types.

Python
try:
    result = "100" + 50
    print(result)

except TypeError:
    print("Cannot add a string and an integer.")
Output:
Cannot add a string and an integer.
5. Handling IndexError

IndexError occurs when you try to access a list or sequence position that does not exist.

Python
try:
    students = ["Rahul", "Priya", "Amit"]

    print(students[5])

except IndexError:
    print("Student position does not exist.")
Output:
Student position does not exist.
6. Handling KeyError

KeyError occurs when a dictionary key does not exist.

Python
try:
    employee = {
        "name": "Rahul",
        "department": "IT"
    }

    print(employee["salary"])

except KeyError:
    print("Salary information is not available.")
Output:
Salary information is not available.
7. Handling FileNotFoundError

When a program attempts to read a file that does not exist, Python raises FileNotFoundError.

Python
try:
    with open("customers.txt", "r") as file:
        data = file.read()

    print(data)

except FileNotFoundError:
    print("Customer file was not found.")
Output:
Customer file was not found.
8. Multiple except Blocks

A program can have multiple except blocks to handle different types of exceptions separately.

Python
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.")
Sample Output:
Please enter a valid integer.
9. Using else with try-except

The else block runs only when the try block completes successfully.

Python
try:
    number = int("100")

except ValueError:
    print("Invalid number.")

else:
    print("Number converted successfully.")
    print("Value:", number)
Output:
Number converted successfully.
Value: 100
10. Using finally

The finally block executes whether an exception occurs or not. It is commonly used for cleanup.

Python
try:
    number = 10 / 2
    print(number)

except ZeroDivisionError:
    print("Cannot divide by zero.")

finally:
    print("Operation completed.")
Output:
5.0
Operation completed.
11. Real-Time Example: ATM Withdrawal

An ATM application can use exception handling to validate withdrawal requests and prevent unexpected failures.

Python
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.")
Sample Output:
Enter withdrawal amount: 12000
Transaction failed: Insufficient balance.
Thank you for using the ATM.
12. Real-Time Example: Login Validation

A login system can handle missing data and invalid input without crashing the application.

Python
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.")
Sample Output:
Username: rahul
Password: wrong123
Login failed: Incorrect password.
13. Real-Time Example: Product Price Calculation

An e-commerce application can use exception handling when calculating prices from user or external data.

Python
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)
Sample Output:
Enter product price: 500
Enter quantity: 3
Total price: โ‚น 1500.0
14. Raising an Exception with raise

The raise statement allows a program to intentionally generate an exception when a business rule is violated.

Python
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)
Output:
Registration failed: Customer must be at least 18 years old.
15. Getting Exception Details

You can store the exception object in a variable using as and display its message.

Python
try:
    result = 10 / 0

except ZeroDivisionError as error:
    print("Error:", error)
Output:
Error: division by zero
16. Catching Multiple Exceptions Together

Related exceptions can be handled by passing them as a tuple to a single except block.

Python
try:
    value = int(input("Enter a number: "))
    result = 100 / value

except (ValueError, ZeroDivisionError):
    print("Please enter a valid non-zero number.")
Sample Output:
Please enter a valid non-zero number.
17. Custom Exception

You can create your own exception class when an application needs a meaningful domain-specific error.

Python
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)
Output:
Transaction failed: Insufficient account balance.
18. Real-Time Example: Bank Account

A bank account can use a custom exception to prevent a withdrawal from exceeding the available balance.

Python
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)
Output:
Withdrawal successful.
Remaining balance: 7000
19. Real-Time Example: File Processing

Exception handling is useful when applications read configuration files, reports, customer records, or logs.

Python
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.")
Sample Output:
Employee data loaded successfully.
Employee records...
File processing completed.
20. Exception Handling in Functions

Functions can contain exception handling so that callers receive a safe result instead of an unexpected crash.

Python
def calculate_average(total, count):

    try:
        return total / count

    except ZeroDivisionError:
        return 0


print(calculate_average(500, 5))
print(calculate_average(500, 0))
Output:
100.0
0
21. Common Python Exceptions
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
22. Complete Real-Time Example: Online Order System

This example combines input validation, custom exceptions, try, except, else, and finally in a small order-processing application.

Python
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)
Output:
Order placed successfully.
Product: Laptop
Quantity: 2
Total: โ‚น 110000
Order processing completed.
23. Exception Handling Best Practices
1. Catch Specific Exceptions

Prefer except ValueError over a completely generic except.

2. Keep try Small

Put only the code that may fail inside the try block.

3. Use finally for Cleanup

Use finally for operations that must happen regardless of success or failure.

4. Use raise

Use raise when application rules are violated.

5. Create Custom Exceptions

Use custom exception classes for meaningful application-specific errors.

6. Avoid Silent Failures

Do not hide errors without providing useful handling or logging.

๐Ÿ’ก Key Idea: Exception handling is not about hiding errors. It is about detecting expected failure conditions, responding safely, and allowing an application to continue when appropriate.
24. Important Exception Handling Rules
try

Contains code that may raise an exception.

except

Handles one or more exceptions.

else

Executes only when the try block succeeds.

finally

Executes whether an exception occurs or not.

raise

Manually raises an exception.

Custom Exception

Creates application-specific error types.

Python Exception Handling

    try โ€ข except โ€ข else โ€ข finally โ€ข raise โ€ข Custom Exceptions