Saturday, 25 July 2026

πŸš€ Day 91/150 – Custom Exceptions in Python

 

πŸš€ Day 91/150 – Custom Exceptions in Python

Python provides many built-in exceptions like ValueError, TypeError, and ZeroDivisionError. But sometimes you may need to create your own exception to represent specific errors in your program. This is called a custom exception.

In this post, we'll learn four ways to work with custom exceptions in Python.


Method 1 – Creating a Basic Custom Exception

Create your own exception by inheriting from the built-in Exception class.

class AgeError(Exception): pass age = int(input("Enter your age: ")) if age < 18: raise AgeError("You must be at least 18 years old.") print("Access Granted!")





Sample Input

16

Output

AgeError: You must be at least 18 years old.

Explanation
  • AgeError is a custom exception class.
  • raise is used to manually trigger the exception.
  • If the age is less than 18, Python raises AgeError.

Method 2 – Handling a Custom Exception

You can catch your custom exception using try and except.


class AgeError(Exception):

pass try: age = int(input("Enter your age: ")) if age < 18: raise AgeError("You must be at least 18 years old.") print("Access Granted!") except AgeError as error: print(error)













Sample Input
15

Output

You must be at least 18 years old.

Explanation

  • The custom exception is raised inside the try block.
  • The except block catches AgeError.
  • The program continues instead of crashing.

Method 3 – Custom Exception with a Custom Message

You can define your own message inside the exception class.


class NegativeNumberError(Exception): def __init__(self): super().__init__("Negative numbers are not allowed.") num = int(input("Enter a number: ")) if num < 0: raise NegativeNumberError() print("Valid Number")










Sample Input
-8

Output
Negative numbers are not allowed.

Explanation
  • The constructor (__init__) defines a default error message.
  • Whenever the exception is raised, the message is displayed automatically.

Method 4 – Custom Exception in a Function

Custom exceptions are commonly used inside functions.

class PasswordError(Exception): pass def check_password(password): if len(password) < 8: raise PasswordError("Password must contain at least 8 characters.") return "Password Accepted" try: print(check_password(input("Enter password: "))) except PasswordError as error: print(error)










Sample Input

python

Output

Password must contain at least 8 characters.

Explanation

  • The function checks the password length.
  • If the password is too short, it raises a custom exception.
  • The exception is caught outside the function using try and except.

Comparison of Methods

MethodBest Used For
Basic Custom ExceptionCreating your own exception type
Custom Exception with try/exceptHandling custom errors gracefully
Custom MessageProviding meaningful error messages
Function-based ExceptionValidating function inputs

πŸ”₯ Key Takeaways

  • A custom exception is a user-defined exception created by inheriting from the Exception class.
  • Use the raise keyword to trigger a custom exception.
  • Catch custom exceptions using try and except.
  • Custom exceptions make your programs easier to understand and debug.
  • They are useful for validating user input and enforcing application-specific rules.
  • Giving custom exceptions meaningful names and messages makes your code more readable.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (319) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) Books (305) Bootcamp (13) C (78) C# (12) C++ (83) cloud (1) Course (87) Coursera (302) Cybersecurity (33) data (10) Data Analysis (40) Data Analytics (29) data management (16) Data Science (406) Data Strucures (23) Deep Learning (206) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (12) flask (4) flutter (1) FPL (17) Generative AI (77) Git (12) Google (54) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (360) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (15) PHP (20) Projects (34) Python (1414) Python Coding Challenge (1204) Python Mathematics (8) Python Mistakes (51) Python Quiz (580) Python Tips (27) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (52) Udemy (18) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)