No announcement
 

Exception Handling

If an exception is not handled in a program, the program will terminate abnormally and display message along with the exception and stack trace. A method can catch an exception using the try-catch construct. Surround the code in try-catch that may generate error. If an error is occurred, then code inside catch block is executed. If no error is encountered then catch block is not executed.

Example:

ExceptionHandlingDemo.java

package com.codingnous.tutorial;

public class ExceptionHandlingDemo {

	public static void main(String[] args) {

		// Declare and initialize variable.
		int i = 10, j = 0;

		// Surround code with try-catch that may generate error.
		try {
			System.out.println("i/j= " + (i / j));
		} catch (ArithmeticException e) {
			System.out.println("Illegal value in division operation.");
		}
	}
}

Output
Illegal value in division operation.

We can catch multiple type of exception by adding additional catch block one after the another. Also, if we want to free up some resource after execution of try block (and no error has occurred) then we can use the finally block.

Example:

MultipleCatchFinallyDemo.java

package com.codingnous.tutorial;

public class MultipleCatchFinallyDemo {

	public static void main(String[] args) {

		// Declare and initialize variable.
		int[] val = { 10, 0 };

		// Surround code with try-catch that may generate error.
		try {
			System.out.println("i/j= " + (val[0] / val[2]));
		} catch (ArithmeticException e) {
			System.out.println("Illegal value in division operation.");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Specified array index does not exist!");
		} finally {
			System.out.println("Finally block will always be executed.");
		}
	}

}

Output
Specified array index does not exist Finally block will always be executed.