🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

finally Block

AI & DATA SCIENCE // finally

The finally block runs after try/catch, regardless of whether an error was thrown. Used for cleanup.

Syntax

try {
  // risky code
} catch (e) {
  // handle error
} finally {
  // ALWAYS runs
}

Deep Dive Course

**finally** runs after the try and catch blocks, whether or not an error occurred, and even if there's a `return` in the try or catch. It's essential for cleanup: closing database connections, hiding loading spinners, releasing file handles. If finally itself throws, that new error replaces the previous one.

1Understanding finally Block

finally runs after the try and catch blocks, whether or not an error occurred, and even if there's a return in the try or catch. It's essential for cleanup: closing database connections, hiding loading spinners, releasing file handles. If finally itself throws, that new error replaces the previous one.

💡

finally runs even after return statements in try/catch. The return value from finally overrides any return in try/catch — be careful.

editor.html
async function fetchWithCleanup() {
  let connection;
  try {
    connection = await openDB();
    return await connection.query('SELECT * FROM users');
  } catch (e) {
    console.error('DB error:', e.message);
    return [];
  } finally {
    // ALWAYS close connection, even on error
    if (connection) await connection.close();
    console.log('Connection closed');
  }
}
localhost:3000

2Practical Example

Here is a real-world application of finally Block showing how it is used in production JavaScript code.

editor.html
// finally with UI state
async function loadData() {
  showSpinner();
  try {
    const data = await fetch('/api/data').then(r => r.json());
    renderData(data);
  } catch (e) {
    showErrorMessage(e.message);
  } finally {
    hideSpinner(); // always hide, even on error
  }
}
localhost:3000

3Best Practices

Follow these guidelines when working with finally Block:

1. Use finally for cleanup: connections, UI state, file handles

2. Keep finally blocks small and side-effect only

3. Don't return from finally unless intentional (it overrides try/catch return)

⚠️

Tip: finally runs even after return statements in try/catch. The return value from finally overrides any return in try/catch — be careful.

editor.html
async function fetchWithCleanup() {
  let connection;
  try {
    connection = await openDB();
    return await connection.query('SELECT * FROM users');
  } catch (e) {
    console.error('DB error:', e.message);
    return [];
  } finally {
    // ALWAYS close connection, even on error
    if (connection) await connection.close();
    console.log('Connection closed');
  }
}
localhost:3000

Examples

Example 01Basic Usage
async function fetchWithCleanup() {
  let connection;
  try {
    connection = await openDB();
    return await connection.query('SELECT * FROM users');
  } catch (e) {
    console.error('DB error:', e.message);
    return [];
  } finally {
    // ALWAYS close connection, even on error
    if (connection) await connection.close();
    console.log('Connection closed');
  }
}
Example 02Advanced Example
// finally with UI state
async function loadData() {
  showSpinner();
  try {
    const data = await fetch('/api/data').then(r => r.json());
    renderData(data);
  } catch (e) {
    showErrorMessage(e.message);
  } finally {
    hideSpinner(); // always hide, even on error
  }
}

Best Practices

  • Use finally for cleanup: connections, UI state, file handles
  • Keep finally blocks small and side-effect only
  • Don't return from finally unless intentional (it overrides try/catch return)

Interview Question

What happens if both catch and finally have return statements?

Hint: Finally overrides.

The return in finally OVERRIDES the return in catch (and try). The value from finally is what the function ultimately returns. This is a subtle but dangerous behavior — avoid returning from finally unless you explicitly intend to override the try/catch result.

Exercises

MediumPractice using finally Block in a real scenario.
View Solution
async function fetchWithCleanup() {
  let connection;
  try {
    connection = await openDB();
    return await connection.query('SELECT * FROM users');
  } catch (e) {
    console.error('DB error:', e.message);
    return [];
  } finally {
    // ALWAYS close connection, even on error
    if (connection) await connection.close();
    console.log('Connection closed');
  }
}

Frequently Asked Questions

What happens if both catch and finally have return statements?

The return in finally OVERRIDES the return in catch (and try). The value from finally is what the function ultimately returns. This is a subtle but dangerous behavior — avoid returning from finally unless you explicitly intend to override the try/catch result.

Related Functions

trycatchthrowPromisesawait