Social Media

2/11/2019

Explicitly raising and handling of Exception

Explicitly raising and implicitly handling:

x=int(input("Enter first number "))
y=int(input("Enter second number "))
if y==0:
    raise ZeroDivisionError("Cannot divide by zero")
rslt=x/y
print("The result is",rslt)

if y=0 then output of above script can be as:
Enter first number 1
Enter second number 0
Traceback (most recent call last):
  File "/root/Desktop/p1.py", line 4, in <module>
    raise ZeroDivisionError("Cannot divide by zero")
ZeroDivisionError: Cannot divide by zero # message will be printed here


Explicitly raising and implicitly handling:

a=int(input("Enter first number "))
b=int(input("Enter second number "))
try:
    if b==0:
        raise ZeroDivisionError("Cannot divide by zero")
    rslt=a/b
    print("The result is",rslt)
except ZeroDivisionError as e:
    print("This is exception:",e)
finally:
    print("This program is created by Mayank Kumar Prajapati")


if b=0 then output of above script is as:
Enter first number 1
Enter second number 0
This is exception: Cannot divide by zero
This program is created by Mayank Kumar Prajapati


Be First to Post Comment !
Post a Comment