OCJP

Finally in Java Programs

As we have learnt basics of Exception handling with try.catch in Java. There is another block called ‘finally’ . When you place any code inside finally block then it is gurantee that if execution is entered in try block then finally block will sure execute even if ‘return’ statement is executed in try block.

class Finallydemo{
	public static void main(String []a){
	int x,y,z=0;
	try{
	x=Integer.parseInt(a[0]);
	y=Integer.parseInt(a[1]);
	//x=2;
	//y=2;
		if(x==y) {
			return;
		}
	z=x/y;
	System.out.println("Ans :"+ z);
	
	}catch(ArrayIndexOutOfBoundsException e){
		System.out.println("Must Provide Two Values");
	}
	catch(ArithmeticException e) {
		System.out.println("Second Value can not be Zero");
	}
	catch(Exception e) {
		e.printStackTrace();
	}
	finally {
		System.out.println("Always Execute if enter in Try Block");
	}
	
	System.out.println("May Not Execute if Program returns before this statment");
	}
}

Leave a Reply

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


× How can I help you?