How to continue program after exception in java

How to continue program after exception in java ?

The below program won’t continue the program execution after the exception:

[java highlight=”8,12,16″]
package in.javadomain;

public class RunAfterException {

public static void main(String[] args) {
int firstVal = 10;
int secondVal = 12;
try {
String[] mobileCompanies = { "Nokia", "Samsung", "sony" };
String anyOneCompany = mobileCompanies[3];
System.out.println("Total is " +(firstVal + secondVal));
} catch (java.lang.ArrayIndexOutOfBoundsException ae) {
System.out.println("Exception occured so I wont give the total of "
+ firstVal + " and " + secondVal + "");

}

}

}

[/java]

Output:

[plain gutter=”false”]Exception occured so I wont give the total of 10 and 12[/plain]

But the below program continue the execution even after exception,

[java highlight=”8,11,15″]
package in.javadomain;

public class RunAfterException {

public static void main(String[] args) {
int firstVal = 10;
int secondVal = 12;
try {
String[] mobileCompanies = { "Nokia", "Samsung", "sony" };
String anyOneCompany = mobileCompanies[3];
} catch (java.lang.ArrayIndexOutOfBoundsException ae) {
System.out.println("Exception occured");

}
System.out.println("Total is " + (firstVal + secondVal));
}

}

[/java]

Output:

[plain gutter=”false”]
Exception occured so I wont give the total of 10 and 12
Total is 22
[/plain]

Note: We have just changed try, catch locations.

Recommended Books:

Leave a Reply