Instagram
youtube
Facebook
Twitter

Exception handling program using Java HackerRank Solutions

Problem:

You will be given two integers x and y as input, you have to compute x/y. If x and y are not 32 bit signed integers or if y is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.

Sample Input 0:

10
3

Sample Output 0:

3

Sample Input 1:

10
Hello

Sample Output 1:

java.util.InputMismatchException

Sample Input 2:

java.lang.ArithmeticException: / by zero

Sample Input 3:

23.323
0

Sample Output 3:

java.util.InputMismatchException

Solution:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);

        try {
           
            int x = scanner.nextInt();
            int y = scanner.nextInt();

            int result = x / y;

            System.out.println(result);

        } catch (java.util.InputMismatchException e) {
            System.out.println("java.util.InputMismatchException");

        } catch (ArithmeticException e) {
            System.out.println("java.lang.ArithmeticException: / by zero");

        } finally {
            scanner.close();
        }
        
    }
}

Steps involved in this solution:

1. The code starts with import statements, bringing in necessary classes from the java.io, java.util, java.text, and java.math packages.

2. The Solution class is declared, which is the main class containing the main method.

3. The main method is the entry point of the program. It initializes a Scanner to read input from the standard input (keyboard).

4. The core logic is enclosed in a try-catch block. This block attempts to read two integers (x and y) from the user input.

5. If the input is successfully read, the program proceeds to perform the division (x / y).

6. Two catch blocks handle potential exceptions:

  • If the input is not an integer (caught by java.util.InputMismatchException), it prints "java.util.InputMismatchException".
  • If the denominator (y) is zero (caught by ArithmeticException), it prints "java.lang.ArithmeticException: / by zero".

7. The finally block ensures that the Scanner is closed, preventing resource leaks.

8. The program reads input, attempts the division, handles exceptions, and closes resources, ensuring a clean execution

9. To test the code, run the program and provide input as described in the prompt. Observe how it handles valid and invalid inputs, and check the output messages for different scenarios.