Exceptions · interview question
Type the exact output of this program.
What does this code output?Hard
Console.WriteLine(Test());
static int Test()
{
int x = 1;
try
{
return x;
}
finally
{
x = 2;
Console.WriteLine("finally");
}
}Answer and explanation
Correct answer
Output:
finally
1Why
The return value (1) is evaluated and stored before finally runs. finally prints its line and changes the local x, but that doesn't affect the value already being returned. Main then prints 1.
Test yourself on Exceptions
A free test with instant, explained results. No account needed.