Interesting Facts In Exception Handling In java

In previous post we have learn about how to do exception handling in java .Now we will discuss some tricky things about exception in java

1. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

}
}

Explanation : when the statement arr[10]=100  encounter to compiler so exception occur and compiler check matching catch block and produce message  according it.
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
2. What will Output Of This Program:

public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
int j=10/0;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

}
}

Output:
java.lang.ArithmeticException: / by zero
3. What will Output Of This Program:
 
 
package exception_handling;
public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];
try {
arr[10]=100;
System.out.println(“You Are In Catch Block”);
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
System.out.println(“You Are In Main Method”);
}
}
Explanation : when the statement arr[10]=100  encounter to compiler so exception occur . Now compiler ignore remaining  try block and check matching catch block and produce message  according it and continue to flow of program.
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
You Are In Main Method

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

51 + = 52