Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs

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):
pass

This 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 = 40
if 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:

  • PasswordError
  • BalanceError
  • AgeError
  • AttendanceError

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!