PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Finally Block in Java

← All stacks

Theory

93/270

Finally Block in Java

finally runs after try (and catch, if any). Use it for cleanup: close file, close connection. It runs whether an error happened or not — that is the point.

try-with-resources often replaces manual finally for Closeable things, but viva still asks finally. A return inside try still hits finally before leaving.

Don’t put the real business result only in finally. finally is cleanup, not the main logic.

Let's take this on the board with one tiny Main class — no extra files. Finally Block in Java — output: Cannot divide then finally always. catch handles /0; finally still runs. Start from main, go line by line, and stop at each print. That output is the proof for Finally Block.

Exam tip

Say: finally always runs for cleanup. Then mention try-with-resources as the modern close.

Example

public class Main {
  public static void main(String[] args) {
    try {
      System.out.println("try");
    } finally {
      System.out.println("finally always");
    }
  }
}

Finally Block in Java — output: Cannot divide then finally always. catch handles /0; finally still runs.

Short notes

  • Deffinally = cleanup after try. Runs whether error happened or not.
  • UseClose file / connection.
  • Rememberreturn in try still runs finally first.
  • TrapUsing finally for main logic instead of cleanup.

Questions

1

When does finally run?

2

What is finally for?

Previous← Nested Try Block in JavaNextJava Throw Exception →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.