try and catch

Enclose the code that you want to monitor inside a try block and catch clause.

The following program includes a try block and a catch clause that processes the ArithmeticException generated by the division-by-zero error:


public class Main {
  public static void main(String args[]) {
    int d, a;
    try { // monitor a block of code.
      d = 0;
      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.");
    }
    System.out.println("After catch statement.");
  }
}

This program generates the following output:


Division by zero.

Once an exception is thrown, program control transfers out of the try block into the catch block. Execution never returns to the try block from a catch.

The following code handles an exception and move on.

 
import java.util.Random;

public class Main {
  public static void main(String args[]) {
    int a = 0, b = 0, c = 0;
    Random r = new Random();
    for (int i = 0; i < 32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b / c);
      } catch (ArithmeticException e) {
        System.out.println("Division by zero.");
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}
  
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions