Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with Finally Block in Java

[post-views]

 

 

In this lesson, you will learn

  • Working with Finally Block
  • Examples

 

Understanding the ‘finally’ block

  • The finally block contains code that is always executed after the try and catch blocks, regardless of whether an exception was thrown or caught.
  • It’s typically used for cleanup code, like closing file streams or database connections.

 

Syntax

try {
    // Code that might throw an exception
} catch (ExceptionType name) {
    // Handling code
} finally {
    // Cleanup code, always executed
}

 

Example: Using Finally Block

package l4;

public class FinallyBlockExample {

	public static void main(String[] args) {
		try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught ArrayIndexOutOfBoundsException: "
        + e.getMessage());
        } finally {
            System.out.println("This will always be printed.");
        }
	}
}

 

Output

 Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
This will always be printed.

 

Note: The finally clause is optional. However, each try statement requires at least one catch or a finally clause otherwise the compilation error will occur.

 

Example: Try block without catch or finally

public class CompileTimeExample {

	public static void main(String[] args) {
		int x;
		try {
			x=10/0;
		} 
	}
}

 

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert "Finally" to complete TryStatement

	at stringdemo.CompileTimeExample.main(CompileTimeExample.java:9)

 

Try with only Finally Block

  • A try block followed by a finally block without a catch block is a valid construct

 

Here’s what happens in different scenarios:

  • If no exception occurs in the try block, the finally block executes and then the control moves to the next part of the code.
  • If an exception occurs in the try block and is not caught (because there is no catch block), the finally block still executes. After the finally block completes, the exception is propagated up the call stack to be handled elsewhere.

 

Syntax

try {
    // Code that might throw an exception
} 
finally {
    // Cleanup code, always executed
}

 

Example: Try-Finally Block

package l4;

public class FinallyBlockExample2 {

	public static void main(String[] args) {
		try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
        } 
		finally {
            System.out.println("This will always be printed.");
        }
		System.out.println("Exiting application.....");
	}
}

 

Output

This will always be printed.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
Index 3 out of bounds for length 3
	at l4.FinallyBlockExample2.main(FinallyBlockExample2.java:7)

 

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review

 

 

Layer 1
Login Categories