Java Exception Handling (Try-catch)

  • + 0 comments

    done under Java 8

    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 x = sc.nextInt();
                int y = sc.nextInt();
                int res = x / y;
                System.out.println(res);
            }
            catch(InputMismatchException ime) {
                System.out.println("java.util.InputMismatchException");
            }
            catch(ArithmeticException ae) {
                System.out.println("java.lang.ArithmeticException: / by zero");
            }
            finally{
                sc.close();
            }
        }
    }