In this Exceptions solution, we need to develop a python program that can use the try and except blocks to find the errors and print the error on the output screen.


HackerRank Exceptions solution in python


Problem solution in Python 2 programming.

for t in xrange(int(input())):
    try:
        a,b = map(int,raw_input().split())
        print a/b
    except ZeroDivisionError as e:
        print "Error Code: %s" % e
    except ValueError as e:
        print "Error Code: %s" % e 


Problem solution in Python 3 programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
    try:
        a,b=map(int,input().split())
        print(a//b)
    except Exception as e:
        print("Error Code:",e)


Problem solution in pypy programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
#from __future__ import division
for i in xrange(input()):
    try:
        a,b = map(int, raw_input().split())
        print a/b
    except Exception as e:
        if isinstance(e, ZeroDivisionError):
            stringy = str(e).split()
            stringy.insert(2, "or")
            stringy.insert(3, "modulo")
            print 'Error Code:'," ".join(map(str, stringy))
        else:
            print 'Error Code:',e
        


Problem solution in pypy3 programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT

from sys import stdin,stdout
n = stdin.readline()

for i in range(0,int(n)):
    line = stdin.readline().strip('\n\r')
    a,b = line.split(" ")
    
    try:
        print(str(int(a)//int(b)))
    except ZeroDivisionError as e:
        print("Error Code: {}".format(e))
    except ValueError as e:
        print("Error Code: {}".format(e))