Java catch Keyword

Java Catch Keyword


Catch Keyword In Java
The catch is used in exception handling 
As we have already studied, catch keyword as the name suggests, used to catch exceptions which are thrown by try keyword, in other words - 
If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner.
Now we will see an example-
Example - 
The following program includes a try block and a catch clause that processes the ArithmeticException generated by the division-by-zero error:
package javaLearnings;
import java.util.Scanner;

public class Main {
  public static void main(String args[]){
      int x, a;
      try { // monitor a block of code.
          x = 0;
          a = 32 / x;
          System.out.println("This will not be printed.");
      } catch (ArithmeticException e) { // catch divide-by-zero error
          System.out.println("Division by zero.");
      }
      System.out.println("After catch statement.");
          }
      }





 
Output - 
 
Multiple catch clauses
In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
Example - 
package javaLearnings;
import java.util.Scanner;

public class Main {
  public static void main(String args[]){
      try {
          int a = args.length;
          System.out.println("a = " + a);
          int b = 42 / a;
          int c[] = { 1 };
          c[42] = 99;
      } catch(ArithmeticException e) {
          System.out.println("Divide by 0: " + e);
      } catch(ArrayIndexOutOfBoundsException e) {
          System.out.println("Array index oob: " + e);
      }
      System.out.println("After try/catch blocks.");
          }
      }

 
Output -