Challenge - 5 Problems
Finally Block Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of finally block with return
What is the output of this JavaScript code?
function test() {
try {
return 'try';
} finally {
return 'finally';
}
}
console.log(test());Javascript
function test() { try { return 'try'; } finally { return 'finally'; } } console.log(test());
Attempts:
2 left
π‘ Hint
Remember that the finally block runs after try and can override return values.
β Incorrect
In JavaScript, if both try and finally blocks have return statements, the return in finally overrides the one in try.
β Predict Output
intermediate2:00remaining
Finally block execution with thrown error
What will be logged to the console?
try {
throw new Error('Oops');
} finally {
console.log('Cleanup');
}Javascript
try { throw new Error('Oops'); } finally { console.log('Cleanup'); }
Attempts:
2 left
π‘ Hint
The finally block runs even if an error is thrown.
β Incorrect
The finally block runs and logs 'Cleanup'. The error is thrown but not caught, so it appears as an uncaught error after the log.
β Predict Output
advanced2:00remaining
Return value with try, catch, and finally
What is the output of this code?
function example() {
try {
throw 'error';
} catch (e) {
return 'catch';
} finally {
return 'finally';
}
}
console.log(example());Javascript
function example() { try { throw 'error'; } catch (e) { return 'catch'; } finally { return 'finally'; } } console.log(example());
Attempts:
2 left
π‘ Hint
Consider which return statement takes priority.
β Incorrect
The finally block's return overrides the catch block's return, so 'finally' is returned.
β Predict Output
advanced2:00remaining
Finally block with thrown error and catch
What will be the output?
try {
throw 'fail';
} catch (e) {
console.log('Caught:', e);
throw 'new fail';
} finally {
console.log('Finally block');
}Javascript
try { throw 'fail'; } catch (e) { console.log('Caught:', e); throw 'new fail'; } finally { console.log('Finally block'); }
Attempts:
2 left
π‘ Hint
The finally block runs after catch, even if catch throws again.
β Incorrect
The catch block logs 'Caught: fail' and throws a new error. The finally block runs and logs 'Finally block'.
π§ Conceptual
expert3:00remaining
Effect of finally on thrown error propagation
Consider this code:
What will be printed to the console?
function f() {
try {
throw 'error';
} finally {
return 'finally';
}
}
try {
console.log(f());
} catch (e) {
console.log('Caught:', e);
}What will be printed to the console?
Attempts:
2 left
π‘ Hint
A return in finally overrides thrown errors.
β Incorrect
The throw in try is overridden by the return in finally, so no error propagates and 'finally' is printed.