Sunday, 31 March 2013

nested try statement

// An example of nested try statements.
class Myjava {
public static void main(String args[]) {
try {
int a =2; //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);
try { // nested try block
/* If one command-line arg is used,
then a 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);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}



C:\>java Myjava
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java Myjava One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java Myjava One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

1 comment:

  1. Thanks :-) also visit rakeshandroid.blogspot.in for mobile application articles ..

    ReplyDelete