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:

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 + "");

		}

	}

}

Output:

Exception occured so I wont give the total of 10 and 12

But the below program continue the execution even after exception,

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));
	}

}

Output:

Exception occured so I wont give the total of 10 and 12
Total is 22

Note: We have just changed try, catch locations.

Recommended Books:

178 total views, 2 views today

Leave a Reply

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