HackerRank Java- Exception Handling (Try-catch)

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 is zero, exception will occur and you have to report it. Read sample Input/Output to know what to report in case of exceptions.

  1. import java.util.*;
  2. public class Solution {
  3. public static void main(String[] args) {
  4. Scanner scan = new Scanner(System.in);
  5. try {
  6. int x = scan.nextInt();
  7. int y = scan.nextInt();
  8. System.out.println(x / y);
  9. } catch (InputMismatchException e) {
  10. System.out.println(e.getClass().getName());
  11. } catch (ArithmeticException e) {
  12. System.out.println(e.getClass().getName() + ": / by zero");
  13. }
  14. }
  15. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]

donate a cup of tea :)

Join Our Facebook Group

Share this solution


Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube