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
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
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));
}
}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 - HashMapPractice on your own: Online Java compiler