Menu
CoddyTech

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

The type in the catch parentheses decides which errors that block handles. Two common ones are ArithmeticException, thrown by an integer division by zero, and NumberFormatException, thrown by Integer.parseInt() when the text is not a number. A single catch can handle several types at once:

try {
   int value = Integer.parseInt(text);
   int result = 10 / value;
} catch (ArithmeticException | NumberFormatException e) {
   // handles both
} finally {
   // always runs
}

Catching Exception instead is broader: it handles both of them and any other exception.

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

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

Practice on your own: Online Java compiler