Monday, 6 January 2020

User Defined Exception Example

##creating our own exceptions
class MyException(Exception):
    def __init__(self,arg):
        self.msg=arg
##wrte code where exception may raise
##to raise exception,use raise statement
def withdraw(dict):
    pin=(int)(input("enter your pin number"))
    for i,info in dict.items():
        for key in info:
            if pin!=info["pin"]:
                print("Wrong pin number")
                break
            else:
                amount=(float)(input("enter amout to be drawn"))
                if(amount>20000):
                    raise MyException('u can draw only 20k ')
                else:
                    print("ur transaction is successful")
                    info['balance']=info['balance']-amount
                    print("available balance=",info['balance'])
            break
         
         
        break
bank = { 2032:{'pin' : 121, 'name' : 'Rama', 'balance' : 25000},
         2033:{'pin' : 122, 'name' : 'Sita', 'balance' : 38900}}
try:
    withdraw(bank)
except MyException as me:
    print(me)
"""output:
case1:
enter your pin number121
enter amout to be drawn23000
u can draw only 20k
case2:
enter your pin number121
enter amout to be drawn1000
ur transaction is successful
available balance= 24000.0
"""
Example 2:

class Error(Exception):
    pass
class StringTooLength(Error):
    pass
class StringTooShort(Error):
    pass
n=10
while True:
    try:
        a=input("enter your name")
        b=len(a)
        if b<n:
            raise StringTooShort
        elif b>n:
            raise StringTooLength
        break
    except StringTooShort:
        print("Your string should be 10 character")
    except StringTooLength:
        print("Your string is too length, try again")
   
print("Success")

"""output:
enter your name Rajendra prasad
Your string is too length, try again
enter your name R
Your string should be 10 character
enter your name Rajendra
Your string should be 10 character
enter your name Hyderabadd

============== RESTART: F:/Programs/exceptions/Userdefined/2.py ==============
enter your name Hyderabadd
Success


What is pass?
"pass" is a keyword that is used to execute nothing; it means, when we don't want to execute code, the pass can be used to execute empty.
If we want to bypass any code pass statement can be used.


No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...