Java Exception Handling (Try-catch)

  • + 1 comment

    Didn't mentioned need to handle different exceptions differently in the question, but apparently that's how they wanted.

        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 scanner = new Scanner(System.in);
            try{
                int x = scanner.nextInt();
                int y = scanner.nextInt();
                System.out.println(x/y);
            }catch(Exception e){
                if (e instanceof InputMismatchException){
                    System.out.println(e.getClass().getName());
                } else {
                    System.out.println(e);
                }
                
            }
    
        }