Hanwool Codes RSS Tag Admin Write Guestbook
2023-03-01 03:30:00

Exceptions | HackerRank

 

Exceptions | HackerRank

Handle errors detected during execution.

www.hackerrank.com

 

Goal

 

You are given two values  a and b.
Perform integer division and print a / b .

 

Solution

 

We use Exceptions to handle errors for this task. 

Here is code explanation.

It reads the input from standard input and then loops for n times, 

where n is the number entered as the first input.

Inside the loop, it reads two integers from the input, performs integer division, and prints the result. 

 

However, if there is a ZeroDivisionError, 

it prints a custom error message saying "Error Code: integer division or modulo by zero"

If there is a ValueError, it prints "Error Code:" followed by the error message.

 

The try block contains the code that might raise an exception

and the except block is where the exception is handled. 

In this code, there are two except blocks, one for ZeroDivisionError and another for ValueError.

 

The ZeroDivisionError occurs when dividing by zero, which is not possible in arithmetic. 

The ValueError occurs when the input cannot be converted to an integer

such as when the input is a string or a floating-point number.

 

By handling these exceptions, the code prevents the program from crashing 

and provides a useful error message to the user.

# Exceptions

# Enter your code here. Read input from STDIN. Print output to STDOUT
for i in range(int(input())):
    
    try:
        values = input().split()
        print(int(int(values[0]) / int(values[1])))
        
    except ZeroDivisionError as ze:
        print("Error Code: integer division or modulo by zero")
        #print("Error Code:",ze) if you use this one, Error Code: division by zero. it is not correct answer for them.
    
    except ValueError as ve:
        print("Error Code:",ve)
Hanwool Codes. Designed by 코딩재개발.