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

Published: 05 January 2018
on channel: 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...


On this page of the site you can watch the video online Lesson - 45 : Python3 - Python Exception Handling : Creating custom exception class with a duration of hours minute second in good quality, which was uploaded by the user Sada Learning Hub 05 January 2018, share the link with friends and acquaintances, this video has already been watched 424 times on youtube and it was liked by 5 viewers. Enjoy your viewing!