Java

What Is Catch Keyword In Java?

A try-catch block employs the catch keyword. A catch block always follows a try block, and if an exception arises inside the try block, the associated catch block takes care of it. Catch blocks are used to deliver informative error messages.

try{
  //statements
}catch(Exception e){
    //exception handling statements
 }

Example of catch keyword

If an error arises: Dividing an integer by zero causes an ArithmeticException to be raised. The matching catch block handles the raised exception if the code that causes it is included inside a try block.

public class JavaExample {
  public static void main(String[] args) {
    try{
      int num1 = 100, num2 =0;
      int quotient = num1/num2;
      System.out.println(quotient);
    }catch(ArithmeticException e){
      System.out.println("Cannot divide a number by zero");
    }
  }
}

Output:

Cannot divide a number by zero

If an exception is not thrown: If an exception is not thrown inside a try block, the catch block is not executed, and the program continues to function as it would without try-catch blocks.

public class JavaExample {
  public static void main(String[] args) {
    try{
      int num1 = 100, num2 =10;
      int quotient = num1/num2;
      System.out.println(quotient);
    }catch(ArithmeticException e){
      System.out.println("Cannot divide a number by zero");
    }
  }
}

Output:

10

Example 2: Multiple catch blocks

public class JavaExample {
  public static void main(String[] args) {
    try{
      int[] arr = {2, 4, 6, 8, 10};
      //arr valid indexes are from 0 till 4
      System.out.println(arr[9]);
    }catch(ArithmeticException e){
      System.out.println("Cannot divide a number by zero");
    }catch(ArrayIndexOutOfBoundsException e){
      System.out.println("Access array elements within limits");
    }catch(Exception e){
      //This is a generic exception handler, if the exception is
      //not caught by previous catch blocks, then it would be
      //handled here, All exception classes comes under Exception class
      System.out.println("There is an issue with the code inside try");
    }
  }
}

Output:

Access array elements within limits

Points to Remember:

  • A try block may include more than one catch block.
  • Without a try block, a catch block is not possible.
  • Catch does not run if an exception does not arise.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button