CodeBlanks Logo Icon CodeBlanks

finally

Learn the finally block.

finally always runs

The finally block always runs, whether or not an exception occurs. It is used to clean up resources (closing files, releasing connections).

try {
  int r = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Hata");
} finally {
  System.out.println("Temizlik");
}

finally comes after catch; it can also be used with a try alone. Even if the exception is caught, finally is guaranteed to run before the program ends. This makes it a safe way to prevent resource leaks.

finally works without catch

finally can be used without a catch. In this case the exception is not caught but cleanup still happens; the exception propagates upward.

try {
  int r = 10 / 0;
} finally {
  System.out.println("Temizlik");
}

This structure is useful in code that does not want to handle the error but still wants to close the resource. try-with-resources is a shorter alternative. Writing return inside finally is technically possible but should be avoided, as it can cause surprising results.

Practice Write try/catch/finally

Divide int a = 10; int b = 0;. Wrap in try; catch ArithmeticException and print Hata. In a finally block print Temizlik.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    int a = 10;
    int b = 0;
    // attempt the division, catch the error, clean up with finally
  }
}

Sample solution

Main.java
try {
  int result = a / b;
  System.out.println(result);
} catch (ArithmeticException e) {
  System.out.println("Hata");
} finally {
  System.out.println("Temizlik");
}

Expected output

Hata
Temizlik

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add the finally block

Question
try {
  int r = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Hata");
} ____ {
  System.out.println("Temizlik");
}
Answer
try {
  int r = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Hata");
} finally {
  System.out.println("Temizlik");
}

Explanation: finally comes after catch and always runs.

2 Match each block to when it runs

Term Meaning
try Risky code
catch On error
finally Always
else Not in try

3 When does the finally block run?

  • Only when there is an exception
  • Never
  • Always (whether or not there is an exception) Correct answer
  • Only when there is no exception

Explanation: finally runs in every case, whether or not an exception occurs.

All lessons in Beginner