finally Always Runs
Completed
Write static int parseOrDefault(String s) that tries Integer.parseInt, returns -1 on failure, and prints checked S in a finally block. Read tokens and print each result after the check message.
Input
n, then n tokens.
Output
Two lines per token.
Example
Input
3 42 hi 7
Output
checked 42 42 checked hi -1 checked 7 7
Editor
Java
Hints
finally runs even when the try block returns.
Solution explanation
finally is for cleanup that must happen no matter how the block exits.
Show solution
import java.util.Scanner;
public class Main {
static int parseOrDefault(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return -1;
} finally {
System.out.println("checked " + s);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(parseOrDefault(sc.next()));
}
}
}