Java Exception Handling (Try-catch) | HackerRank Solution

Hello coders, today we are going to solve Java Exception Handling (Try-catch) HackerRank Solution.

Try-catch

Problem

Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. (Wikipedia)

Java has built-in mechanism to handle exceptions. Using the try statement we can test a block of code for errors. The catch block contains the code that says what to do if exception occurs.

This problem will test your knowledge on try-catch block.

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

 10
 0

Sample Output 2

 java.lang.ArithmeticException: / by zero

Sample Input 3

 23.323
 0

Sample Output 3

 java.util.InputMismatchException

Solution – Java Exception Handling (Try-catch)

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try{
            Scanner sc = new Scanner(System.in);
            int a = sc.nextInt();
           
            int b = sc.nextInt();
          
            int c = a/b;
            System.out.print(c);
        }
        catch(InputMismatchException ob){
            System.out.print("java.util.InputMismatchException");
        }
        catch(Exception e)
        {
            System.out.print(e);
        }
    }
}

Disclaimer: The above Problem ( Java Exception Handling (Try-catch) ) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published.