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

Pubblicato il: 05 gennaio 2018
sul canale di: 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...


In questa pagina del sito puoi guardare il video online Lesson - 45 : Python3 - Python Exception Handling : Creating custom exception class della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Sada Learning Hub 05 gennaio 2018, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 424 volte e gli è piaciuto 5 spettatori. Buona visione!