Challenge - 5 Problems
Finally Block Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of try-catch-finally with return
What is the output of this Java code?
Java
public class Test { public static int testMethod() { try { return 1; } catch (Exception e) { return 2; } finally { System.out.println("Finally block executed"); } } public static void main(String[] args) { System.out.println(testMethod()); } }
Attempts:
2 left
π‘ Hint
Remember that finally block runs even if there is a return in try.
β Incorrect
The finally block runs before the method returns. So it prints first, then the return value is printed.
β Predict Output
intermediate2:00remaining
Finally block with exception thrown
What is the output of this Java code?
Java
public class Test { public static void main(String[] args) { try { throw new RuntimeException("Error"); } finally { System.out.println("Finally block runs"); } } }
Attempts:
2 left
π‘ Hint
Finally block runs even if exception is thrown.
β Incorrect
The finally block executes before the exception is propagated, so its message prints first.
β Predict Output
advanced2:00remaining
Finally block overriding return value
What is the output of this Java code?
Java
public class Test { public static int test() { try { return 10; } finally { return 20; } } public static void main(String[] args) { System.out.println(test()); } }
Attempts:
2 left
π‘ Hint
Finally block return overrides try return.
β Incorrect
If finally block has a return statement, it overrides any previous return.
β Predict Output
advanced2:00remaining
Finally block with exception and catch
What is the output of this Java code?
Java
public class Test { public static void main(String[] args) { try { int a = 5 / 0; } catch (ArithmeticException e) { System.out.println("Catch block"); } finally { System.out.println("Finally block"); } } }
Attempts:
2 left
π‘ Hint
Catch runs first, then finally.
β Incorrect
Exception is caught, so catch block runs, then finally block runs.
π§ Conceptual
expert2:00remaining
Finally block and System.exit() behavior
What happens when System.exit() is called inside a try block with a finally block present?
Attempts:
2 left
π‘ Hint
System.exit() stops JVM immediately.
β Incorrect
System.exit() terminates the JVM immediately, so finally block is skipped.