Java Tutorial Java Advanced Java References

Java catch Keyword



When Java interpreter executes a program and encounters an error or exception, it usually stops and throws error message. To handle such situation, Java has three keywords:

  • try: It is used to test a block of statements for error.
  • catch: It has a block of statements which executes when error occurs and handles error.
  • finally: It has a block of statements which executes regardless of try-catch blocks result.

try-catch blocks

In the example below, z is undefined, which raises an error. As the error occurred in try block of statement, it will be handled by its catch block of statement. Without try block, the program will stop immediately after an error and throw error message.

Syntax

try{
  statements;
}
catch (Exception e){
  statements;
}

Example:

public class MyClass {
  public static void main(String[] args) {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (Exception e){
      System.out.println("An error occurred.");
    }
  }
}

The output of the above code will be:

An error occurred.

Many catch blocks

A Java program can have multiple catch blocks to handle each type of exception differently.

Syntax

try{
  statements;
}
catch (ExceptionType_1 e){
  statements;
}
catch (ExceptionType_2 e){
  statements;
} 
...
...
catch (Exception e){
  statements;
}

Example:

In the example below, z is undefined and raises ArithmeticException. Hence, the respective catch block of code is executed when the error occurs.

public class MyClass {
  public static void main(String[] args) {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (NumberFormatException e){
      System.out.println("Number Format error.");
    }
    catch (ArithmeticException e){
      System.out.println("Arithmetic operation error.");
    }   
    catch (Exception e){
      System.out.println("An error occurred.");
    }
  }
}

The output of the above code will be:

Arithmetic operation error.

❮ Java Keywords