JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

22. Exception handling



This chapter covers how JavaScript handles exceptions.

As an aside: JavaScript didn’t support exceptions until ES3. That explains why they are used sparingly by the language and its standard library.

22.1. Motivation: throwing and catching exceptions

Consider the following code. It reads profiles stored in files into an Array with instances of class Profile:

function readProfiles(filePaths) {
  const profiles = [];
  for (const filePath of filePaths) {
    try {
      const profile = readOneProfile(filePath);
      profiles.push(profile);
    } catch (err) { // (A)
      console.log('Error in: '+filePath, err);
    }
  }
}
function readOneProfile(filePath) {
  const profile = new Profile();
  const file = openFile(filePath);
  // ··· (Read the data in `file` into `profile`)
  return profile;
}
function openFile(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error('Could not find file '+filePath); // (B)
  }
  // ··· (Open the file whose path is `filePath`)
}

Let’s examine what happens in line B: An error occurred, but the best place to handle the problem is not the current location, it’s line A. There, we can skip the current file and move on to the next one.

Therefore:

When we throw, the following constructs are active:

readProfiles(···)
  for (const filePath of filePaths)
    try
      readOneProfile(···)
        openFile(···)
          if (!fs.existsSync(filePath))
            throw

throw walks up this chain of constructs, until it finds a try statement. Execution continues in the catch clause of that try statement.

22.2. throw

throw «value»;

Any value can be thrown, but it’s best to throw instances of Error:

throw new Error('Problem!');

22.2.1. Options for creating error objects

22.3. try-catch-finally

The maximal version of the try statement looks as follows:

try {
  // try_statements
} catch (error) {
  // catch_statements
} finally {
  // finally_statements
}

The try clause is mandatory, but you can omit either catch or finally (but not both). Since ECMAScript 2019, you can also omit (error), if you are not interested in the value that was thrown.

22.3.1. The catch clause

If an exception is thrown in the try block (and not caught earlier) then it is assigned to the parameter of the catch clause and the code in that clause is executed. Unless it is directed elsewhere (via return or similar), execution continues after the catch clause: with the finally clause – if it exists – or after the try statement.

The following code demonstrates that the value that is thrown in line A is indeed caught in line B.

const errorObject = new Error();
function func() {
  throw errorObject; // (A)
}

try {
  func();
} catch (err) { // (B)
  assert.equal(err, errorObject);
}

22.3.2. The finally clause

Let’s look at a common use case for finally: You have created a resource and want to always destroy it when your are done with it – no matter what happens while working with it. You’d implement that as follows:

const resource = createResource();
try {
  // Work with `resource`: errors may be thrown.
} finally {
  resource.destroy();
}

The finally is always executed – even if an error is thrown (line A):

let finallyWasExecuted = false;
assert.throws(
  () => {
    try {
      throw new Error(); // (A)
    } finally {
      finallyWasExecuted = true;
    }
  },
  Error
);
assert.equal(finallyWasExecuted, true);

The finally is always executed – even if there is a return statement (line A):

let finallyWasExecuted = false;
function func() {
  try {
    return; // (A)
  } finally {
    finallyWasExecuted = true;
  }
}
func();
assert.equal(finallyWasExecuted, true);

22.4. Error classes and their properties

Quoting the ECMAScript specification:

22.4.1. Properties of error classes

Consider err, an instance of Error:

const err = new Error('Hello!');
assert.equal(String(err), 'Error: Hello!');

Two properties of err are especially useful:

Note that logging an error usually also displays a stack trace:

console.log(err);
// Error: Hello!
//   at repl:1:11
//   at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//   ···

  Exercise: Exception handling

exercises/exception-handling/call_function_test.js