Sunday, 29 November 2020

User defined Exceptions in Python

#USER DEFINED EXCEPTION

Here MyException is an userdefined class and it must be inherited from the base class Exception.

Create a constructor and send the error message to it.

class MyException(Exception):
    def __init__(self,value):
        self.value=value
    def __str__(self):
        return(repr(self.value))
try:
    raise(MyException("This is my user defined Exception"))
except MyException as e:
    print("Printable Message:",e.value)

#USER DEFINED EXCEPTION WITH INHERITANCE 

class MyException(Exception):
     pass
class Dividebyzero(MyException):
      pass
try:
    a = int(input("Enter a value: "))
    b=int(input("Enter b value: "))
    if b==0:
        raise Dividebyzero
    else:
        print("result=",(a/b))
except Dividebyzero:
    print("Dont enter Input value for b as zero, try again!")
#FINALLY KEYWORD

try:
    a=int(input("enter value for a"))
    b=int(input("enter value for b"))
    c=a/b
    print(c)
except ZeroDivisionError:    
    print("Dont enter b value as zero")    
finally:    
    print('This is always executed')  

No comments:

Post a Comment