skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Sunday, February 12, 2012

Nested Try to Handle Divided by Zero Error

Posted by Admin at 3:54 AM – 0 comments
 
Here is a Java Program to Demonstrate the Nested Try

class MethNestTry {
  static void nesttry(int a) {
    try { // nested try block
      /* If one command line arg is used,
         then an divide-by-zero exception 
         will be generated by the following code. */
      if(a==1) a = a/(a-a); // division by zero

      /* If two command line args are used
         then generate an out-of-bounds exception. */     
      if(a==2) {
        int c[] = { 1 };
        c[42] = 99; // generate an out-of-bounds exception
      }
    } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index out-of-bounds: " + e);
    }
  }

  public static void main(String args[]) {
    try {
      int a = args.length;

      /* If no command line args are present,
         the following statement will generate
         a divide-by-zero exception. */
      int b = 42 / a;

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

      nesttry(a);
    } catch(ArithmeticException e) {
      System.out.println("Divide by 0: " + e);
    }
  }
}

Output of Above Java Program
Divide by 0: java.lang.ArithmeticException: / by zero

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger