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-finally without catch
What is the output of this C# code snippet?
C Sharp (C#)
using System; class Program { static void Main() { try { Console.WriteLine("Start"); } finally { Console.WriteLine("Finally block executed"); } } }
Attempts:
2 left
💡 Hint
Remember that the finally block always runs after the try block, even if no exception occurs.
✗ Incorrect
The try block runs first and prints "Start". Then the finally block runs and prints "Finally block executed". So both lines appear in order.
❓ Predict Output
intermediate2:00remaining
Finally block with exception thrown
What will be printed when this code runs?
C Sharp (C#)
using System; class Program { static void Main() { try { Console.WriteLine("Before exception"); throw new Exception("Error"); } finally { Console.WriteLine("In finally"); } } }
Attempts:
2 left
💡 Hint
The finally block runs even if an exception is thrown, before the exception propagates.
✗ Incorrect
The try block prints "Before exception" then throws. The finally block runs and prints "In finally". Then the exception is unhandled and shown.
❓ Predict Output
advanced2:00remaining
Return value with finally modifying variable
What is the output of this program?
C Sharp (C#)
using System; class Program { static int Test() { int x = 1; try { return x; } finally { x = 2; Console.WriteLine("Finally executed"); } } static void Main() { Console.WriteLine(Test()); } }
Attempts:
2 left
💡 Hint
The return value is determined before finally runs, even if finally changes the variable.
✗ Incorrect
The method returns x which is 1. The finally block runs and prints "Finally executed" but does not change the returned value.
❓ Predict Output
advanced2:00remaining
Finally block with return inside it
What will this program print?
C Sharp (C#)
using System; class Program { static int Test() { try { return 1; } finally { return 2; } } static void Main() { Console.WriteLine(Test()); } }
Attempts:
2 left
💡 Hint
A return in finally overrides any previous return from try.
✗ Incorrect
The finally block's return replaces the try block's return, so the method returns 2.
🧠 Conceptual
expert2:00remaining
Behavior of finally with exception and return
Consider this code snippet. What happens when it runs?
C Sharp (C#)
using System; class Program { static int Test() { try { throw new Exception("Error"); } finally { return 42; } } static void Main() { Console.WriteLine(Test()); } }
Attempts:
2 left
💡 Hint
A return in finally block suppresses any exception thrown in try.
✗ Incorrect
The exception is thrown but the finally block returns 42, which overrides the exception. So 42 is printed and no exception propagates.