Concept Flow - Finally block
Start try block
Execute try code
Error?
Yes→Catch block runs
Execute catch code
Try block ends
Finally block runs
End
The finally block runs after try and catch blocks, no matter if an error happened or not.
try { console.log('Try block'); throw new Error('Oops'); } catch (e) { console.log('Catch block'); } finally { console.log('Finally block'); }
| Step | Action | Output | Next Step |
|---|---|---|---|
| 1 | Enter try block | No output yet | Execute console.log('Try block') |
| 2 | console.log('Try block') | Try block | Throw error new Error('Oops') |
| 3 | throw new Error('Oops') | Error thrown | Jump to catch block |
| 4 | Enter catch block | No output yet | Execute console.log('Catch block') |
| 5 | console.log('Catch block') | Catch block | Enter finally block |
| 6 | Enter finally block | No output yet | Execute console.log('Finally block') |
| 7 | console.log('Finally block') | Finally block | End execution |
| Variable | Start | After Step 3 | After Step 7 |
|---|---|---|---|
| Error thrown | No | Yes (Error object) | Handled (catch) |
try {
// code that may throw
} catch (error) {
// handle error
} finally {
// always runs
}
- finally runs no matter what
- runs after try and catch
- useful for cleanupWhat is the main purpose of the finally block in JavaScript?
Which of the following is the correct syntax to add a finally block after a try and catch block?
try {
// code
} catch (e) {
// handle error
} ??? {
// cleanup code
}What will be the output of this code?
function test() {
try {
console.log('Try block');
return 'Return from try';
} catch (e) {
console.log('Catch block');
} finally {
console.log('Finally block');
}
}
console.log(test());Find the error in this code snippet:
try {
throw new Error('Oops');
} catch {
console.log('Caught error');
} finally {
console.log('Cleanup');
}Consider this code:
let result = '';
function test() {
try {
result += 'Try';
throw new Error('Error!');
} catch (e) {
result += 'Catch';
return result;
} finally {
result += 'Finally';
}
}
test();
console.log(result);What will be printed to the console?
Pass the test and this pattern moves unknown