How to use Java try catch statement

Description

To guard against and handle a run-time error, enclose the code to monitor inside a try block.

Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.

Example


public class Main {
  public static void main(String args[]) {
    try { // monitor a block of code.
      int d = 0;
      int a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }/*  ww w .j ava 2 s .c o m*/
    System.out.println("After catch statement.");
  }
}

The code above generates the following result.

Multiple catch Clauses

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.


public class Main {
  public static void main(String args[]) {
    try {/*  ww w.j  a va  2  s .  com*/
      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.");
  }
}

When you use multiple catch statements, exception subclasses must come before any of their superclasses.

The code above generates the following result.

Nested try Statements

The try statement can be nested.


public class Main {
  public static void main(String args[]) {
    try {/*from   w w w . j  ava2s. c  om*/
      int a = args.length;
      int b = 42 / a;
      System.out.println("a = " + a);
      try { // nested try block
        if (a == 1)
          a = a / (a - a); // division by zero exception
        if (a == 2) {
          int c[] = { 1 };
          c[4] = 9; // an out-of-bounds exception
        }
      } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Array index out-of-bounds: " + e);
      }
    } catch (ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures