JavaScript · Async JavaScript

Error Handling

Things go wrong: bad input, network failures, missing data. Error handling lets your program recover gracefully instead of crashing.

Intermediate 5 min Lesson 31 of 49 Runnable examples
Before you start:Functions
0/49 in JavaScript
On this page · 5 min · Intermediate

Learning objectives#

  • Catch errors with try…catch
  • Run cleanup code in finally
  • Throw meaningful errors
  • Use the right built-in error types

Explanation#

Code inside try runs normally. If anything throws, execution jumps to catch, which receives the error object.

finally runs whether there was an error or not — useful for cleanup such as hiding a loading spinner.

throw new Error('message') creates your own error. Use specific types: TypeError for wrong types, RangeError for out-of-range values.

Every error has name and message properties (and a stack trace for debugging).

Syntax#

JavaScript Illustrative
try {
  riskyCode();
} catch (err) {
  console.log(err.name, err.message);
} finally {
  cleanup();
}

Code example: Validating ages safely#

JavaScriptValidating ages safely Runnable
function parseAge(text) {
  const age = Number(text);
  if (Number.isNaN(age)) throw new TypeError(`"${text}" is not a number`);
  if (age < 0) throw new RangeError('Age cannot be negative');
  return age;
}


for (const input of ['25', 'abc', '-3']) {
  try {
    console.log('Age:', parseAge(input));
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  } finally {
    console.log('checked', input);
  }
}
Expected output
Age: 25
checked 25
TypeError: "abc" is not a number
checked abc
RangeError: Age cannot be negative
checked -3
Opens this example in the full playground

Step-by-step explanation#

  1. parseAge throws a TypeError or RangeError for bad input.
  2. For "25" no error occurs, so catch is skipped.
  3. For "abc" the TypeError is caught and its name and message printed.
  4. finally runs every time, error or not.

Real-world use case#

Showing “Could not load products — try again” instead of a blank page when an API call fails.

Common mistakes#

Empty catch blocks

catch (e) {} hides problems. At least log the error or show a message.

Throwing strings

throw 'oops' has no name or stack trace. Throw Error objects.

Best practices#

  • Catch errors where you can do something useful
  • Throw Error objects with clear messages
  • Use finally for cleanup
  • Log unexpected errors for debugging

Remember this#

try = attempt, catch = rescue, finally = always tidy up.

throw new Error(…), never throw a plain string.

Every error has a name and a message.

Practice exercise#

Your task: Write safeDivide(a, b) that throws a RangeError when b is 0, and call it inside try…catch.

Show solution
JavaScript Runnable
function safeDivide(a, b) {
  if (b === 0) throw new RangeError('Cannot divide by zero');
  return a / b;
}
try { console.log(safeDivide(10, 0)); } catch (e) { console.log(e.message); }
Opens this example in the full playground

Mini quiz#

Error Handling quizTrue or false Question 1 of 1

finally runs only when an error occurred.

Score so far: 0/0

Want more? Practise all JavaScript MCQs · JavaScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.