Hackforge Academy

Category: java

finally

Published on 18 Feb 2026

Explanation

finally is a block in Java used with try and catch. It always executes whether an exception occurs or not.

Code:

try {
    int a = 10 / 2;
} catch (Exception e) {
    System.out.println("Exception caught");
} finally {
    System.out.println("Finally block executed");
}

Explanation

finally is mainly used to close resources like database connections, files, or streams to ensure cleanup.

Code:

try {
    // database code
} finally {
    System.out.println("Closing connection");
}

Explanation

Even if an exception occurs in the try block, the finally block will still execute.

Code:

try {
    int a = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Exception handled");
} finally {
    System.out.println("Always runs");
}

Explanation

A try block can be followed directly by finally without a catch block.

Code:

try {
    System.out.println("Inside try");
} finally {
    System.out.println("Inside finally");
}

Explanation

finally block will not execute only in rare cases like System.exit() call or JVM crash.

Code:

try {
    System.exit(0);
} finally {
    System.out.println("This will not execute");
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community