Skip to main content

Command Palette

Search for a command to run...

34. ASYNC | Error Handling in JavaScript

This article will talk about error handling in javascript.

Updated
•2 min read
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

The try...catch syntax allows us to catch errors so that the script instead of dying can do something more reasonable.

try {
  // try the code
} catch (err) {
  // handle the error
}
💡
The err variable contains the error object.

It works like this:

  1. First, the code in try is executed.

  2. If there is no error, catch is ignored else catch is executed.


The error object

For all the built-in errors, the error object has three main properties viz. 1) name, 2) message and 3) stack.

try {
  // try the code
} catch (err) {
  console.log(err.name);
  console.log(err.message);
  console.log(err.stack);
}

Throwing Custom Error

  • We can throw our own error by using the throw syntax.
if (age>100) {
   throw new Error("Age can't be greater than 100.")
}
  • We can also throw a particular error message by using the built-in constructor for standard errors.
throw new SyntaxError(message)

// OR

throw new ReferenceError(message)

finally block

It runs in all cases:

  • after try if there are no errors.

  • after catch if there are errors.

try {
  // try the code
} catch (err) {
  // handle the error
} finally {
  // runs in all cases
}

If a finally block has a return, it overrides any return from the try (or catch) block.

function test() {
  try {
    return "from try";
  } finally {
    return "from finally";
  }
}

console.log(test()); 

// Output: "from finally"

If finally has no return → original return is preserved.

function test() {
  try {
    return "from try";
  } finally {
    console.log("finally runs");
  }
}

console.log(test());

/* Output:
 finally runs
 from try
*/

Using return inside finally is generally discouraged because:

  • It hides errors.

  • It overrides expected return values.

  • Makes debugging difficult.


try...catch works synchronously

If an error happens in scheduled code like Timers, etc., then try...catch won't catch it.

try {
  setTimeout(() => {
     // some error ocurred
  }, 2000)
} catch (err) {
  // handle the error
}

This is because the scheduled code is executed later when the JS engine has already left the try...catch construct.


Happy learning!