Java Exception Handling (Try-catch)

  • + 0 comments

    Initially in catch block i simply wrote sysout(e); to print exception message.

    But one of the test case failed for arithmetic exception so i used ternery operator like below instaed of writing catch block for all exceptions.

    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 = 0;
            int y = 0;
    
    
            x = sc.nextInt();
            y = sc.nextInt();
    
           System.out.print(x/y);
    
        }catch(Exception e){
            String emsg = (e.getClass().getName().equalsIgnoreCase("java.lang.ArithmeticException")) ? "java.lang.ArithmeticException: / by zero" : e.getClass().getName();
            System.out.print(emsg);
        }
        finally{
            sc.close();
        }
    
    
    
    }
    

    }