Handling of predefined exceptions in Java

Program that illustrates the Handling of predefined exceptions.




import java.util.*;

class Main 

{

 public static void main(String[] args) 

 {

  Scanner scanner = new Scanner(System.in);

  try 

  {

   System.out.print("Enter a number: ");

   int num = scanner.nextInt();

   int result = 10 / num; // This might cause ArithmeticException

   System.out.println("Result: " + result);

  } 

  catch(ArithmeticException e) 

  {

    System.out.println("Error: Cannot divide by zero.");

    System.out.println("Exception Handled.");

  } 

  catch(java.util.InputMismatchException e) 

  {

   System.out.println("Error: Invalid input. Please enter a valid number.");

   System.out.println("Exception Handled.");

  } 

 }

}

Output




Post a Comment

0 Comments