This page looks best with JavaScript enabled

Handle Exceptions in Javascript

 ·   ·  ☕ 3 min read

Get a quick-start on using try/catch to handle errors and exceptions.

Consider the below example that expects name to be provided to the program. If name is provided you will go ahead and store record.

1
2
3
4
5
let name = "";

if (name) {
  // store record
}

The big problem with the above code is absence of any kind of feedback to the caller (or user).

You can do this to manage that error and notify the caller.

1
2
3
4
let name = "";
if (!name) throw "Name is empty. Provide name."; // error with this message

// store record

Execution halts at the if statement if there is an error.

Use a try/catch if you want to handle this much more gracefully.

1
2
3
4
5
6
try {
  let name = "";
  if (!name) throw "Name is empty. Provide name.";
} catch (e) {
  throw e; // error with the above message
}

You could also use try/catch to suppress error, do something, and continue execution.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
try {
  let name = "";
  if (!name) throw "Name is empty. Provide name.";
} catch (e) {
  console.log(e); // Name is empty. Provide name.
  // store error
  // initiate a retry after some time
}

console.log("I can overcome failures"); // I can overcome failures

As you get deeper, you may also want to locally handle exceptions from certain parts of the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
try {
  let name = "";
  if (!name) console.warn("Name is empty.");

  try {
    // commit to database
  } catch (exDb) {
    console.error(exDb);
  }
} catch (e) {
  console.log(e);
}

These are referred to as ‘nested try/catch’ blocks.

When you there is an error in inner block control transfers to inner catch. There after the inner catch can further throw error and transfer control to outer catch. Or, manage the error and let outer try block at peace.

If there is no inner catch block, the exception will go all the way to the outer catch (or to the caller if there is no catch at all).

Finally, use a finally block to execute statements both in case there is no error, or an error was caught.

1
2
3
4
5
6
7
8
try {
  let name = "";
  if (!name) throw "Name is empty. Provide name.";
} catch (e) {
  console.log(e); // Name is empty. Provide name.
} finally {
  console.log("error or not, here I am");
}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things