0
0
Javascriptprogramming~20 mins

Finally block in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Finally Block Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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());
Atry
Bundefined
Cfinally
DError
Attempts:
2 left
πŸ’‘ Hint
Remember that the finally block runs after try and can override return values.
❓ Predict Output
intermediate
2: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');
}
ACleanup\nError: Oops
BNo output
CError: Oops
DCleanup
Attempts:
2 left
πŸ’‘ Hint
The finally block runs even if an error is thrown.
❓ Predict Output
advanced
2: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());
Acatch
Bfinally
Cundefined
Derror
Attempts:
2 left
πŸ’‘ Hint
Consider which return statement takes priority.
❓ Predict Output
advanced
2: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');
}
AFinally block
BFinally block\nCaught: fail
CCaught: fail
DCaught: fail\nFinally block
Attempts:
2 left
πŸ’‘ Hint
The finally block runs after catch, even if catch throws again.
🧠 Conceptual
expert
3:00remaining
Effect of finally on thrown error propagation
Consider this code:
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?
Afinally
BError: error
Cundefined
DCaught: error
Attempts:
2 left
πŸ’‘ Hint
A return in finally overrides thrown errors.