Python 24-Day Course - Day 12: Exception Handling

Day 12: Exception Handling

Basic Exception Handling

try:
    number = int(input("Enter a number: "))
    result = 100 / number
    print(f"Result: {result}")
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")

try-except-else-finally

try:
    f = open("data.txt", "r")
    content = f.read()
except FileNotFoundError:
    print("File not found")
else:
    print(f"File content: {content}")  # Runs only if no error
finally:
    print("Operation complete")  # Always runs

Common Built-in Exceptions

ExceptionWhen It Occurs
ValueErrorInvalid value conversion
TypeErrorInvalid type operation
KeyErrorDictionary key not found
IndexErrorIndex out of range
FileNotFoundErrorFile not found
ZeroDivisionErrorDivision by zero
AttributeErrorAccessing non-existent attribute

Custom Exceptions

class InsufficientBalanceError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(
            f"Insufficient balance: balance {balance}, withdrawal request {amount}"
        )

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(balance, amount)
    return balance - amount

try:
    result = withdraw(1000, 5000)
except InsufficientBalanceError as e:
    print(e)  # Insufficient balance: balance 1000, withdrawal request 5000

Today’s Exercises

  1. Create a function that validates user input to accept only integers between 1 and 100.
  2. Write a safe file reading function that handles all possible exceptions.
  3. Create a NegativeNumberError custom exception and use it in practice.

Was this article helpful?