finally block in exception handling

 

✅ The finally Block in Java

In Java, the finally block is used with try-catch to guarantee execution of a block of code regardless of whether an exception occurs or not. It's commonly used for cleanup operations such as closing files, releasing resources, or resetting values.


🔹 Syntax of try-catch-finally

try {
// Code that might throw an exception } catch (ExceptionType e) { // Exception handling code } finally { // Code that always executes }

📘 Example 1: Basic Use of finally


public class FinallyExample { public static void main(String[] args) { try { int data = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Caught exception: " + e.getMessage()); } finally { System.out.println("Inside finally block – cleanup done."); } } }

Output:

Caught exception: / by zero
Inside finally block – cleanup done.

📘 Example 2: No Exception Occurs

public class FinallyNoException {
public static void main(String[] args) { try { int data = 10 / 2; System.out.println("Result: " + data); } catch (ArithmeticException e) { System.out.println("Exception caught"); } finally { System.out.println("Finally block executed."); } } }

Output:

Result: 5
Finally block executed.

📘 Example 3: Exiting Early with return

Even if you use return inside try or catch, the finally block will still run.

public class FinallyWithReturn {
public static void main(String[] args) { System.out.println(testMethod()); } static String testMethod() { try { return "Try block return"; } catch (Exception e) { return "Catch block return"; } finally { System.out.println("Finally block executed."); } } }

Output:

Finally block executed.
Try block return

✅ Why use finally?

  • To ensure critical code always executes.

  • To release system resources, e.g., close database connections, file streams.

  • To perform consistent cleanup regardless of program state.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism