πŸ”₯ Welcome to my blog! Latest updates available now. Visit daily! πŸ”₯ πŸ”₯ Click Here for Latest Updates – Visit My Blog πŸ”₯
πŸ”₯ Latest Updates πŸ“Š GP Grade Finder πŸ“’ Government Services Info πŸ†• New Schemes Updates

Types of Exceptions in Python

 -->In Python, there are Two types of exceptions:

1.Predefined Exceptions

2.User Defined Exceptions


1. Predefined Exceptions:

-->Also known as in-built exceptions.

The exceptions which are raised automatically by the Python Virtual Machine whenever a particular event occurs are called predefined exceptions.


Example 1:

Whenever we try to perform division by zero, Python raises ZeroDivisionError.


print(10/0)


Example 2:

Whenever we try to convert input value to int type and the input is not an integer, Python raises ValueError.


x = int("ten")   # ValueError


2. User Defined Exceptions:

-->Also known as Customized Exceptions or Programmatic Exceptions.

-->Sometimes we must define and raise exceptions explicitly to indicate that something has gone wrong. Such exceptions are called User Defined Exceptions or Customized Exceptions.


-->The programmer is responsible for defining these exceptions. Python does not know about them, so we must raise them explicitly based on our requirement by using the raise keyword.


Eg:

InsufficientFundsException  

InvalidInputException  

TooYoungException  

TooOldException


-->How to Define and Raise Customized Exceptions:

-->Every exception in Python is a class that extends the Exception class either directly or indirectly.


Syntax:

class classname(predefined exception class name):

    def __init__(self, arg):

        self.msg = arg


Example:

class TooYoungException(Exception):

    def __init__(self, arg):

        self.msg = arg

-->TooYoungException is our class name which is the child class of Exception.

-->We can raise an exception by using the 

raise keyword as follows:

raise TooYoungException("message")


Complete Example:

class TooYoungException(Exception):

    def __init__(self, arg):

        self.msg = arg


class TooOldException(Exception):

    def __init__(self, arg):

        self.msg = arg


age = int(input("Enter Age: "))


if age > 60:

    raise TooYoungException("Plz wait some more time you will get best match soon!!!")

elif age < 18:

    raise TooOldException("Your age already crossed marriage age... no chance of getting marriage")

else:

    print("You will get match details soon by email!!!")


Output:

Enter Age: 12

__main__.TooYoungException: Plz wait some more time you will get best match soon!!!

Copy code


Enter Age: 90

__main__.TooOldException: Your age already crossed marriage age... no chance of getting marriage


Enter Age: 27

You will get match details soon by email!!!


✅Note:πŸ‘‰ raise keyword is best suitable for customized exceptions, but not for predefined exceptions.

No comments:

Post a Comment

Thank you Very Much.For Given Comment

Quatation of the Day 22-03-2026