Java Exception Handling (Try-catch)

  • + 1 comment

    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 c=x/y;
           System.out.println(c);
     }catch(InputMismatchException q){
         System.out.println("java.util.InputMismatchException");
     }
     catch(Exception q){
         System.out.println(q);
     }
    }
    

    }

    • + 1 comment

      why cant we take input before the try block?

      • + 0 comments

        sc.nextInt() is used to read integers from the input. However, if the user enters something that is not an integer (e.g., a letter, a decimal number, or a string), sc.nextInt() will throw an InputMismatchException.so that's why we are using inside the try block.