MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
finally block0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
9.1try...catch9.2finally block9.3Throwing Custom Errors9.4Error Handling in Async Code
HomeTutorialsJavaScript for Intermediatefinally block
Throwing Custom Errors

finally block

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

In mission-critical applications, releasing resources (such as closing database connections, unlocking file handles, or hiding loading spinners) must happen reliably whether an operation completes successfully or crashes midway. The finally clause guarantees execution regardless of the outcome.


1. Syntax & Execution Guarantee

1try {
2 console.log('1. Initiating resource transaction...');
3 performRiskyOperation();
4 console.log('2. Transaction successful!');
5} catch (error) {
6 console.error('2. Transaction failed:', error.message);
7} finally {
8 console.log('3. Cleanup: Releasing lock and closing connection.');
9}

Whether performRiskyOperation() succeeds or throws, step 3 (finally) is always guaranteed to execute.


2. finally Executes Even with Early Return!

A remarkable property of finally is that it executes even if the try or catch block executes an early return statement:

1function processPayment() {
2 try {
3 console.log('Processing payment...');
4 return 'SUCCESS'; // Return statement encountered!
5 } catch (err) {
6 return 'FAILED';
7 } finally {
8 // THIS STILL RUNS BEFORE THE CALLER RECEIVES THE VALUE!
9 console.log('Audit log entry created.');
10 }
11}
12 
13const status = processPayment();
14console.log('Result:', status);

Console Output:

  1. 1
    Processing payment...
  2. 2
    Audit log entry created. (Finally executes first!)
  3. 3
    Result: SUCCESS

3. The Dangerous Anti-Pattern: Returning from finally

If you explicitly return a value from inside the finally block, it will override any previous return value or thrown exception from try or catch:

1function dangerousCode() {
2 try {
3 throw new Error('Fatal Database Crash!');
4 } finally {
5 return 42; // OVERWRITES THE THROWN ERROR!
6 }
7}
8 
9console.log(dangerousCode()); // 42 (The error was completely swallowed!)
Rule of Thumb: Use finally strictly for side-effects and cleanup (closing streams, toggling boolean loading flags, resetting timers). Never return values or throw new errors inside finally.

4. try...finally without a catch Block

You can pair try directly with finally without a catch block. In this scenario, the cleanup code executes, and the exception continues bubbling up to the caller:

1function writeToFile(fileHandle, data) {
2 try {
3 fileHandle.write(data);
4 } finally {
5 // Guarantees file is always closed, even if write() crashes!
6 fileHandle.close();
7 }
8}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
When does the finally block execute?
Question 2
What happens if a function returns 'A' in try, but returns 'B' in finally?
Question 3
Can you have a try statement with a finally block but NO catch block?
Question 4
What is the primary intended use case for a finally block?
Question 5
If an error is thrown in try and swallowed by a return in finally, what does the caller experience?
Next Lesson

Throwing Custom Errors

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
try...catchThrowing Custom Errors

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext