Lesson - 45 : Python3 - Python Exception Handling : Creating custom exception class

Опубликовано: 07 Октябрь 2024
на канале: Sada Learning Hub
424
5

**************************************************
Python Core PlayList :    • Lesson - 01 : Python3 - What is python  
Python Advanced PlayList :    • Lesson - 46 : Python Advanced - Pytho...  
**************************************************
Python Exception Handling : Creating custom exception class:
Exception handling enables you handle errors gracefully and do something meaningful about it. Like display a message to user if intended file not found. Python handles exception using try.. except ..  block.

You can create a custom exception class by Extending BaseException  class or subclass ofBaseException .

Python Exception Handling : Creating custom exception class:
As you can see from most of the exception classes in python extends from theBaseException  class. You can derive you own exception class from BaseException  class or from sublcass of BaseException  like RuntimeError .


Create a new file called NegativeAgeException.py  and write the following code.

class NegativeAgeException(RuntimeError):
    def __init__(self, age):
        super().__init__()
        self.age = age

Above code creates a new exception class named NegativeAgeException , which consists of only constructor which call parent class constructor using super().__init__()  and sets theage .

Python Exception Handling : Creating custom exception class:
Using custom exception class :
def enterage(age):
    if age < 0:
        raise NegativeAgeException("Only positive integers are allowed")
 
    if age % 2 == 0:
        print("age is even")
    else:
        print("age is odd")
 
try:
    num = int(input("Enter your age: "))
    enterage(num)
except NegativeAgeException:
    print("Only positive integers are allowed")
except:
    print("something is wrong")

Sample Projects : https://github.com/SadaLearningHub1/P...