CodeBlanks Logo Icon CodeBlanks

The finally block

JavaScript course · Beginner · Lesson 120/133

Learn finally for cleanup code that runs whether or not an error occurred.

The finally block

The finally block comes after try and catch and always runs whether or not an error occurred. This makes it ideal for cleanup: closing a file, clearing a timer or resetting a flag belongs in finally.

Example: try { riskyCode(); } catch (e) { console.error(e); } finally { cleanup(); }. Here cleanup() runs in both the success and error cases. finally cannot be skipped; even a return still runs finally first.

When to use finally?

finally is used especially for resource cleanup: closing files, cutting database connections, stopping timers. Even if return exits the function, finally still runs; so placing important cleanup code here is safe.

Example: you opened a file and an error occurred during processing. catch handles the error, but closing the file is a job for finally. This way the file always closes and no resource leak occurs. finally is optional; you can also write just try...catch.

Exercise Timer management with try/catch/finally

Define a function called runWithTimer. In a try block call console.time("op"), then call console.log("Running"). In a catch (e) block call console.error(e.message). In a finally block call console.timeEnd("op").

Show example solution
function runWithTimer() {
  try {
    console.time("op");
    console.log("Running");
  } catch (e) {
    console.error(e.message);
  } finally {
    console.timeEnd("op");
  }
}

Test yourself

  1. When does the finally block run?

    try { work(); } catch (e) { log(e); } finally { done(); }
    • Only when try succeeds
    • Only when catch ran
    • Always, whether or not there is an error
    • Only when throw is called
    Show answer

    Always, whether or not there is an error — Correct. finally always runs; the error state does not matter.

  2. Add the finally block

    try {
      startTimer();
    } catch (e) {
      console.error(e);
    } ____ {
      stopTimer();
    }
    Show answer
    try {
      startTimer();
    } catch (e) {
      console.error(e);
    } finally {
      stopTimer();
    }
  3. Match finally usage scenarios

    File opening
    close in finally
    Timer start
    stop in finally
    Flag set
    reset in finally
    Temporary change
    undo in finally

All lessons in Beginner