Handle an exception and move on. : try catch « Statement Control « Java Tutorial






import java.util.Random;

public class MainClass {
  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);
    }
  }
}








4.10.try catch
4.10.1.catch divide-by-zero error
4.10.2.Handle an exception and move on.
4.10.3.Demonstrate multiple catch statements.
4.10.4.Catch different Exception types
4.10.5.An example of nested try statements.
4.10.6.Try statements can be implicitly nested via calls to methods