Thursday, November 24, 2011

ArithmeticException


ArithmeticException is to catch arithmetic errors, like divide by zero. Following is the code that demonstrates this.


packageorg.training.exceptions;

public class Arithmetic {

      public static void main(String[] args) {
           
            int x = 0;
            int y = 10;
            int z = 0;
           
            try {
                  // this is prone for arithmetic exception,
                  z = y / x;
            }catch(ArithmeticException ae) {
                  System.err.println("Arithmetic Exception has been caught, check your code again.");
                  ae.printStackTrace();
            }

      }

}

Output:
Arithmetic Exception has been caught, check your code again.
java.lang.ArithmeticException: / by zero
      at org.training.exceptions.Arithmetic.main(Arithmetic.java:13)

No comments:

Post a Comment