Python Mastery – From Basics to Brilliance / Exception Handling

Custom Exception Classes

Raising Exceptions 🚫

You can throw exceptions manually using raise.

age = -5
if age < 0:
    raise ValueError("Age cannot be negative")

πŸ”Ή Custom Exception Classes 🧨

Create your own exceptions by inheriting from Exception:

class InsufficientBalance(Exception):
    def __init__(self, message):
        super().__init__(message)

balance = 100
withdraw = 200
if withdraw > balance:
    raise InsufficientBalance("Not enough funds!")

βœ… Use custom exceptions to clarify specific types of business logic errors.


πŸ”Ή Common Built-in Exceptions πŸ“›

Exception

When It Occurs

ValueError

Invalid value (e.g., int("abc"))

TypeError

Operation on incompatible types

IndexError

Index out of range in a list

KeyError

Accessing missing dictionary key

ZeroDivisionError

Dividing by zero

FileNotFoundError

File doesn't exist