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
EasyCreate a method named processNumber that takes two arguments:
- A String (
number) to convert to integer - A boolean (
shouldThrow) that determines if an exception should be thrown
The method should:
- Initialize a result variable to 0
- In the try block:
- If shouldThrow is true, divide 10 by 0
- Otherwise, convert the number string to integer and store it in result
- In the catch block: set result to -1
- In the finally block: add 100 to result
- 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 = 3Try 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));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap