HackerRank Java Exception Handling (Try-catch) solution YASH PAL, 31 July 2024 In this HackerRank Java Exception Handling (Try-catch) problem in java programming, 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, an exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions. HackerRank Java Exception Handling (Try-catch) problem 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) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scan = new Scanner(System.in); try { int x = scan.nextInt(); int y = scan.nextInt(); System.out.println(x / y); } catch(ArithmeticException | InputMismatchException e) { if (e instanceof ArithmeticException) { System.out.println("java.lang.ArithmeticException: / by zero"); } else if (e instanceof InputMismatchException){ System.out.println("java.util.InputMismatchException"); } } scan.close(); } } Second 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 in = new Scanner(System.in); try { int a = in.nextInt(); int b = in.nextInt(); System.out.println(a/b); } catch (java.util.InputMismatchException ime) { System.out.println("java.util.InputMismatchException"); } catch (java.lang.ArithmeticException ae) { System.out.println("java.lang.ArithmeticException: / by zero"); } } } The third solution in java8 programming 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. */ Scanner sc=new Scanner(System.in); try{ int a=sc.nextInt(); int b=sc.nextInt(); System.out.println(a/b); } catch(Exception e){ if(e instanceof java.lang.ArithmeticException) System.out.println(e.toString()); if(e instanceof java.util.InputMismatchException) System.out.println("java.util.InputMismatchException"); } } } coding problems hackerrank solutions java