Finally Block in Java

Previous
Next

Finally:

  • ‘finally’ is a keyword.
  • ‘finally’ is a block of statements.
  • ‘finally’ block is used to release(close) any resource connected to program.
  • Finally block executes whether or not an exception has raised in try block.

Catch block doesn’t execute if no exception in try block:

class FinallyBlock 
{
	public static void main(String[] args) 
	{
		try
		{
			int x = 10/5 ;
			System.out.println("try");
		}
		catch (Exception e)
		{
			System.out.println("catch");
		}
		finally
		{
			System.out.println("finally");
		}
	}
}

Try block terminates and catch block executes when exception occurs:

class FinallyBlock 
{
	public static void main(String[] args) 
	{
		try
		{
			int x = 10/0 ;
			System.out.println("try");
		}
		catch (Exception e)
		{
			System.out.println("catch");
		}
		finally
		{
			System.out.println("finally");
		}
	}
}
  • We can define try & finally blocks without catch block.
  • Catch block is used to collect the exception object to be handled.
  • If we don’t catch, the object will be handled by Default exception handler.
class FinallyBlock 
{
	public static void main(String[] args) 
	{
		try
		{
			int x = 10/5 ;
			System.out.println("try");
		}
		finally
		{
			System.out.println("finally");
		}
	}
}
  • If we don’t define the catch block and exception has risen, the program terminates abnormally.
  • ‘finally’ block executes in case of abnormal termination also….
class FinallyBlock 
{
	public static void main(String[] args) 
	{
		try
		{
			int x = 10/0 ;
			System.out.println("try");
		}
		finally
		{
			System.out.println("finally");
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form