Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Lists
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Exception Handling
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- AES-256 Encryption
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Below is a fresh, original, human-style, plagiarism-free article on:
⭐ Custom Exceptions (class CustomError(Exception):) in Python
It includes:
✔ Unique SEO title ✔ 150-character SEO description ✔ 150-character SEO keywords ✔ Detailed explanation ✔ 3 unique example programs per concept ✔ Why the topic is important ✔ Memory tricks for interviews and exams
Written simply and clearly for new learners.
🔵 SEO Title (Unique & Human-Friendly)
Python Custom Exceptions: A Beginner’s Guide to Creating and Using Your Own Error Classes
🟢 SEO Description (150 characters)
Learn Python custom exceptions with clear explanations, real examples, memory tricks, and interview-ready guidance to build safer and cleaner applications.
🟠 SEO Keywords (150 characters)
python custom exceptions, create custom error, python exception class, user defined errors python, exception handling python, python interview prep
✨ Custom Exceptions in Python — Full Beginner-Friendly Guide
Python has many built-in exceptions like ValueError, TypeError, and ZeroDivisionError. However, sometimes these built-in errors are not enough.
In real applications, you often need your own specific error type—something that clearly describes what went wrong.
This is where custom exceptions come in.
Custom exceptions help you label errors in your program with your own meanings, especially when:
- enforcing business rules
- validating user input
- preventing dangerous actions
- handling domain-specific errors
Python makes this very easy using:
class CustomError(Exception): pass--------------------------------------------------------
🟩 1. Creating a Basic Custom Exception
--------------------------------------------------------
A custom exception is simply a new class that inherits from Exception.
Structure:
class MyError(Exception): passThis gives your program a unique error type that you can raise or catch just like built-in exceptions.
⭐ Example 1: Basic Custom Exception for Age Validation
class AgeError(Exception): pass
age = int(input("Enter age: "))
if age < 0: raise AgeError("Age cannot be negative!")else: print("Valid age:", age)⭐ Example 2: Custom Exception for Invalid Marks
class MarksError(Exception): pass
marks = int(input("Enter marks: "))
if marks > 100: raise MarksError("Marks must be between 0 and 100.")else: print("Marks accepted:", marks)⭐ Example 3: Custom Exception for Restricted Username
class UsernameError(Exception): pass
username = input("Enter username: ")
if " " in username: raise UsernameError("Spaces are not allowed in usernames.")else: print("Username saved.")--------------------------------------------------------
🟦 2. Custom Exception with Custom Message
--------------------------------------------------------
Custom exceptions can include:
- your own message
- extra attributes
- custom methods
This makes errors more informative and user-friendly.
⭐ Example 1: Detailed Error for Low Bank Balance
class LowBalanceError(Exception): def __init__(self, balance): self.balance = balance super().__init__(f"Balance too low: {balance}")
balance = 40if balance < 100: raise LowBalanceError(balance)⭐ Example 2: Custom Exception for Invalid Temperature
class TemperatureError(Exception): def __init__(self, temp): self.temp = temp super().__init__(f"Temperature out of safe range: {temp}")
temp = -80
if temp < -50 or temp > 50: raise TemperatureError(temp)⭐ Example 3: Custom Error When File Format Is Wrong
class FileFormatError(Exception): def __init__(self, ext): super().__init__(f"Unsupported file type: {ext}")
file = "photo.txt"extension = file.split(".")[-1]
if extension not in ["png", "jpg"]: raise FileFormatError(extension)--------------------------------------------------------
🟧 3. Raising and Catching Custom Exceptions
--------------------------------------------------------
Just like built-in exceptions, custom ones can be caught using try-except.
⭐ Example 1: Handle Custom Password Error
class WeakPasswordError(Exception): pass
try: pwd = input("Enter password: ") if len(pwd) < 5: raise WeakPasswordError("Password too short!")except WeakPasswordError as e: print("Error:", e)else: print("Password accepted.")⭐ Example 2: Handle Invalid Score with Custom Exception
class ScoreError(Exception): pass
try: score = int(input("Enter score: ")) if score < 0: raise ScoreError("Score cannot be negative!")except ScoreError as e: print("Error:", e)else: print("Score recorded!")⭐ Example 3: Custom Exception for Login Attempts
class LoginError(Exception): pass
try: user = input("Enter username: ") if user != "admin": raise LoginError("Invalid username!")except LoginError as e: print("Login failed -", e)else: print("Login successful!")--------------------------------------------------------
🟫 Why Learning Custom Exceptions Is Important
--------------------------------------------------------
✔ 1. Helps build real-world applications
APIs, databases, banking systems, and web apps use custom exceptions heavily.
✔ 2. Makes your code more readable
Custom names like AgeError, LoginError, or PaymentError tell exactly what went wrong.
✔ 3. Makes debugging easier
You instantly know the source and meaning of the problem.
✔ 4. Ensures strict rule enforcement
Anything outside your custom rules triggers an immediate stop.
✔ 5. Very common interview topic
Interviewers often ask you to create a custom exception class.
--------------------------------------------------------
🔷 How to Remember for Interviews & Exams
--------------------------------------------------------
💡 Memory Trick 1: “Custom = Your Rules”
Whenever you need your own rule → define your own error.
💡 Memory Trick 2: Inherit from Exception
Always remember the format:
class YourError(Exception): pass💡 Memory Trick 3: E-R-C Formula
E– define the Exception class R– raise it C– catch it
💡 Memory Trick 4: Practice Name-Based Errors
Create small programs with meaningful names like:
PasswordErrorBalanceErrorAgeErrorAttendanceError
This sticks in your memory.
💡 Memory Trick 5: Interview Definition
Memorize this simple line:
“A custom exception in Python is a user-defined error class that inherits from Exception.”
🎉 Want the next topic?
I can write on:
- Exception hierarchy
- Raising exceptions (
raise) - Assertions vs custom exceptions
- Final revision notes for exam preparation
Just tell me!