Errors and Exceptions | HackerRank Solution

admin
By -
0

In this problems we just need to take T as int and had to take t -times  inputs a,b  pairs with each lins

and then  try to  divides them return zerodivisionerror or value error according what pair value passed and we have to  handle multiple values  and multiple errors and exception at same time and return for each instance.



What we Doing


In Python, you can handle multiple types of exceptions within a single try-except block by specifying different exception types in separate except clauses. This allows you to manage various error situations effectively during runtime. For example, when performing division, if the denominator is zero, it raises a ZeroDivisionError, and if non-numeric values are provided, a ValueError might occur.

You can handle both errors separately, allowing you to give specific feedback to the user for each case.

You can also catch multiple exceptions in a single except clause by specifying them in a tuple, making your code more concise while still distinguishing between different error types. Additionally, using a generic except Exception block allows you to catch unforeseen errors that may arise during execution. This way, the program can handle any kind of input issues or unexpected failures without crashing.


Problem: https://www.hackerrank.com/challenges/exceptions/problem?isFullScreen=true

Code:


#Naive Code
T = int(input())
store = []
for _ in range(T):
    a,b = str(input()).split()
    store.append((a,b))
for x,y in store:  
    try:
        print(int(x)//int(y))
    except ValueError as e:
        print("Error Code:", e)
    except ZeroDivisionError as e:
        print("Error Code:", e)




#More Optimized Code.
T = int(input())
#Handle Multiple Error and Exception on same time.
for _ in range(T):
    a, b = input().split()
    try:
        a = int(a)
        b = int(b)
        print(a // b)  
       
    except ValueError as e:
        print(f"Error Code: {e}")  # Handle invalid integer input
    except ZeroDivisionError as e:
        print(f"Error Code: {e}")  # Handle division by zero

If this works for you please comment your thought with us and if had any better solution as well put.

Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*