Menu
Coddy logo textTech

Finally Block

Part of the Logic & Flow section of Coddy's Java journey — lesson 41 of 59.

The finally block contains code that will be executed after try-catch blocks, whether an exception occurs or not. It's commonly used for cleanup operations like closing files or database connections.

Here's the basic structure of a try-catch-finally block:

try {
   // Code that might throw an exception
} catch (ExceptionType e) {
   // Code to handle the exception
} finally {
   // Code that always executes
}

Let's see an example with a counter:

int counter = 0;
try {
   int result = 10 / 0;
   // This will throw an exception
   counter = 1;
} catch (ArithmeticException e) {
   counter = 2;
} finally {
   counter = 3;
   // This will always execute
}

After executing the above code, counter contains:

3

challenge icon

Challenge

Easy

Create a method named processNumber that takes two arguments:

  1. A String (number) to convert to integer
  2. A boolean (shouldThrow) that determines if an exception should be thrown

The method should:

  1. Initialize a result variable to 0
  2. In the try block:
    • If shouldThrow is true, divide 10 by 0
    • Otherwise, convert the number string to integer and store it in result
  3. In the catch block: set result to -1
  4. In the finally block: add 100 to result
  5. Return result as a string

Cheat sheet

The finally block executes after try-catch blocks, regardless of whether an exception occurs. It's used for cleanup operations.

Basic structure:

try {
   // Code that might throw an exception
} catch (ExceptionType e) {
   // Code to handle the exception
} finally {
   // Code that always executes
}

Example with counter:

int counter = 0;
try {
   int result = 10 / 0; // throws exception
   counter = 1;
} catch (ArithmeticException e) {
   counter = 2;
} finally {
   counter = 3; // always executes
}
// counter = 3

Try it yourself

import java.util.Scanner;

public class Main {
    public static String processNumber(String number, boolean shouldThrow) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String number = scanner.nextLine();
        boolean shouldThrow = Boolean.parseBoolean(scanner.nextLine());
        
        System.out.println(processNumber(number, shouldThrow));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow