Thursday, November 10, 2011

Statement Control » try catch

catch divide-by-zero error
public class MainClass {
  public static void main(String args[]) {
    int d, a;

    try {
      d = 0;
      a = 42 / d;
      System.out.println("This will not be printed.");
    catch (ArithmeticException e) { // 
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}
 
Handle an exception and move on.
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);
    }
  }
}
 
Demonstrate multiple catch statements
class MultiCatch {
  public static void main(String args[]) {
    try {
      int a = args.length;
      System.out.println("a = " + a);
      int b = 42 / a;
      int c[] };
      c[4299;
    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.");
  }
}
 
Catch different Exception types
class MyException extends Exception {
  MyException() {
    super("My Exception");
  }
}

class YourException extends Exception {
  YourException() {
    super("Your Exception");
  }
}

class LostException {
  public static void main(String[] args) {
    try {
      someMethod1();
    catch (MyException e) {
      System.out.println(e.getMessage());
    catch (YourException e) {
      System.out.println(e.getMessage());
    }
  }

  static void someMethod1() throws MyException, YourException {
    try {
      someMethod2();
    finally {
      throw new MyException();
    }
  }

  static void someMethod2() throws YourException {
    throw new YourException();
  }
}
 
An example of nested try statements.
class NestTry {
  public static void main(String args[]) {
    try {
      int a = args.length;

      int b = 42 / a;

      System.out.println("a = " + a);

      try {
        if (a == 1)
          a = a / (a - a)// division by zero

        if (a == 2) {
          int c[] };
          c[4299// generate 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);
    }
  }
}
 
 
http://www.java2s.com/Tutorial/Java/0080__Statement-Control/Catalog0080__Statement-Control.htm

No comments:

Post a Comment