0
0
Javascriptprogramming~5 mins

Finally block in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the finally block in JavaScript?
The finally block contains code that always runs after the try and catch blocks, no matter if an error occurred or not.
Click to reveal answer
beginner
When does the code inside a finally block execute?
It executes after the try block finishes, whether an error was thrown or not, and after the catch block if an error was caught.
Click to reveal answer
intermediate
Can the finally block change the return value of a function?
Yes, if the finally block contains a return statement, it overrides any previous return from try or catch.
Click to reveal answer
advanced
What happens if an error is thrown inside the finally block?
The error thrown in finally will replace any previous error or return value, and it will propagate out of the whole try-catch-finally structure.
Click to reveal answer
beginner
Write a simple example of a try-catch-finally block in JavaScript.
try { console.log('Try block runs'); throw new Error('Oops'); } catch (e) { console.log('Catch block runs:', e.message); } finally { console.log('Finally block always runs'); }
Click to reveal answer
When does the finally block run in a try-catch-finally statement?
AOnly if an error occurs
BOnly if no error occurs
CAlways, after try and catch blocks
DNever
What happens if there is a return statement inside both try and finally blocks?
AThe return in <code>finally</code> overrides the one in <code>try</code>
BAn error occurs
CBoth returns are ignored
DThe return in <code>try</code> is used
If an error is thrown inside the finally block, what happens?
AThe error replaces any previous error or return
BThe error is ignored
CThe program continues without error
DThe error is caught automatically
Which of these is a correct use of finally?
ATo catch errors thrown in <code>try</code>
BTo clean up resources like closing files or connections
CTo declare variables
DTo skip code execution
Can a finally block exist without a catch block?
AOnly in strict mode
BNo, <code>catch</code> is required
COnly in older JavaScript versions
DYes, <code>finally</code> can follow <code>try</code> directly
Explain the role of the finally block in JavaScript error handling and when it executes.
Think about what code you want to run no matter what happens in try or catch.
You got /3 concepts.
    Describe what happens if a return statement is present in both the try and finally blocks.
    Consider which return value the function actually sends back.
    You got /3 concepts.