Java Tutorial Java Advanced Java References

Java try 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.

❮ Java Keywords