The finally Block Always Runs
Problem
Read an integer n. Print the trace of a try / catch / finally block, one word per line. First print try. If n is negative the block throws an error: print error. Otherwise print ok. At the end always print finally.
Constraints
- -10^9 <= n <= 10^9
Examples
Input
-1
Output
try error finally
Input
5
Output
try ok finally
Solutions
finally is used to release resources (files, connections) even when an error happens. In Java, try-with-resources does this automatically for AutoCloseable objects.
/*
* Problem : Trace.
* Input : One integer n.
* Output : Three or four words.
* Approach: try / catch / finally.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(long n) {
java.util.List<String> trace = new java.util.ArrayList<>();
try {
// Step 1: The try block runs first.
trace.add("try");
if (n < 0) {
throw new IllegalArgumentException("negative");
}
trace.add("ok");
} catch (IllegalArgumentException error) {
// Step 2: The catch block runs only if an error was thrown.
trace.add("error");
} finally {
// Step 3: The finally block runs in every case, with or without an error.
trace.add("finally");
}
return trace.toArray(new String[0]);
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(String.join("\n", solve(n)));
}
}
Hints (1)
- When does finally not run?