Error and Exception Handling

By Syncfusion®, Inc. · Last updated

What an error is, the three kinds of error, and how exceptions work, then try, catch and finally, throwing your own errors with clear messages, the error object, the built-in error types and handling JSON.parse() failures.

What Is Error Handling?

Error = JavaScript saying "I cannot do this". It stops the code at that line. Error handling = code that deals with the problem calmly, so the program carries on.

  • try runs code that might fail.
  • catch handles the failure.
  • finally always runs, for clean-up. throw raises your own error.

Simple lesson: an error does not have to crash your program. Catch it, deal with it, carry on.

A Real-World Example

A shop loads 100 orders, and order 42 has broken data. Without error handling, orders 42 to 100 never show. With try/catch around each order, order 42 shows "could not be read", and the other 99 appear.

try

catch

finally: runs every time (clean-up)

The broken order drops into catch. The others keep moving.

Some boxes stop with an error on purpose. Their titles say so.

What You Will Learn

  1. Syntax, runtime and logical errors.
  2. What an exception is, and how it differs from an error.
  3. try, catch and finally.
  4. throw and clear custom messages.
  5. The error object, the built-in error types, and safe JSON.parse().

Introduction to Error Handling

What is an Error?

The first line prints. Then customer is undefined, so reading name fails, and nothing after it runs.

Reading a property of a missing customer stops the program

const customer = undefined;

console.log("Looking up the customer...");
console.log(customer.name);
console.log("This line never runs.");

Why Error Handling is Important

One broken order stops the loop, so order 103 is never processed. We fix this later.

One broken order stops the other orders from being processed

const orders = [
  { id: 101, items: ["Pen", "Notebook"] },
  { id: 102, items: null },
  { id: 103, items: ["Stapler"] },
];

for (const order of orders) {
  console.log(`Order ${order.id} has ${order.items.length} item(s)`);
}

An error does not have to crash your program. Catch it, deal with it, and carry on.

Types of Errors

They differ in when they show up. That decides whether code can respond.

Syntax Error

Broken grammar, like a missing ). JavaScript reads the whole file first, so nothing runs, not even line 1.

A missing closing bracket stops even the first line

console.log("Starting the checkout...");
console.log("Total:", 250;

Runtime Error

Valid code, but a value is wrong when the line runs. Earlier lines do run.

The code is valid, but the cart is null when push runs

let cart = null;

console.log("Adding a book to the cart...");
cart.push("Book");

Logical Error

No error at all, just a wrong answer. Here only 70 is divided by 3. The fix is (80 + 90 + 70) / 3.

Three test scores, and an average that is far too high

const average = 80 + 90 + 70 / 3;

console.log("Average score:", average);

Expected output:

Average score: 193.33333333333334

Logical errors are the hardest to find: nothing is reported. Check results against an answer you can work out by hand.

Introduction to Exception Handling

What is an Exception?

Exception = a runtime error that is thrown so another part of the code can catch it.

The same null cart, but this time the exception is caught

try {
  const cart = null;
  cart.push("Book");
} catch (error) {
  console.log("An exception was caught:", error.message);
}

console.log("The program is still running.");

Expected output:

An exception was caught: Cannot read properties of null (reading 'push')
The program is still running.

Why "exception"? It is an exception to the normal flow: JavaScript jumps to the catcher instead of the next line.

Why Exception Handling is Important

Each order gets its own try. Order 102 still fails, but order 103 is processed.

Each order is handled separately, so order 103 is still processed

const orders = [
  { id: 101, items: ["Pen", "Notebook"] },
  { id: 102, items: null },
  { id: 103, items: ["Stapler"] },
];

for (const order of orders) {
  try {
    console.log(`Order ${order.id} has ${order.items.length} item(s)`);
  } catch (error) {
    console.log(`Order ${order.id} could not be read: ${error.message}`);
  }
}

Expected output:

Order 101 has 2 item(s)
Order 102 could not be read: Cannot read properties of null (reading 'length')
Order 103 has 1 item(s)

Error vs Exception

Error = the problem. Exception = that problem being thrown to a catcher. Only runtime errors become exceptions.

A try block does not catch a wrong answer, because nothing was thrown

try {
  const average = 80 + 90 + 70 / 3;
  console.log("Average score:", average);
} catch (error) {
  console.log("Caught:", error.message);
}
KindWhen it shows upBecomes an exception?
Syntax errorbefore the program startsNo, the program never runs
Runtime errorwhile a line runsYes, it can be caught
Logical errornever reportedNo, nothing is thrown

Exception Handling

try

Holds the code that might fail. At the first line that throws, the rest of try is skipped.

The line after the failure inside try is skipped

const steps = [];

try {
  steps.push("reading the price");
  const price = null;
  steps.push(`price has ${price.toFixed(2)}`);
  steps.push("price formatted");
} catch (error) {
  steps.push("caught the problem");
}

console.log(steps);

Expected output:

[
  "reading the price",
  "caught the problem"
]

catch

Runs only when try throws. catch (error) receives the error object. Return a safe value, report it, or throw again.

catch receives the error and decides what to do next

function readQuantity(order) {
  try {
    return order.quantity.toFixed(0);
  } catch (error) {
    console.log("Could not read the quantity:", error.message);
    return "0";
  }
}

console.log("Quantity:", readQuantity({ quantity: 3 }));
console.log("Quantity:", readQuantity({}));

Expected output:

Quantity: 3
Could not read the quantity: Cannot read properties of undefined (reading 'toFixed')
Quantity: 0

If you do not need the error object, write just catch { ... }.

Never leave a catch empty. It hides the problem, and a stranger error appears later.

finally

Runs every time: after success, after a caught failure, even after a return. Use it for clean-up, like switching off "loading".

The loading flag is switched off on success and on failure

let loading = false;

function loadProfile(name) {
  loading = true;
  try {
    if (name === "") throw new Error("A name is required");
    return `Loaded profile for ${name}`;
  } catch (error) {
    return `Failed: ${error.message}`;
  } finally {
    loading = false;
  }
}

console.log(loadProfile("Asha"), "| loading:", loading);
console.log(loadProfile(""), "| loading:", loading);

Expected output:

Loaded profile for Asha | loading: false
Failed: A name is required | loading: false

Never return inside finally. It replaces the real result and even swallows a thrown error.

Throwing Exceptions

throw

throw new Error("message") stops the function and hands the error to the nearest catch. A function can say "no" loudly instead of returning a wrong value.

withdraw refuses an amount larger than the balance

function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Not enough money in the account");
  }
  return balance - amount;
}

try {
  console.log("New balance:", withdraw(500, 200));
  console.log("New balance:", withdraw(500, 900));
} catch (error) {
  console.log("Withdrawal failed:", error.message);
}

Expected output:

New balance: 300
Withdrawal failed: Not enough money in the account

Always throw an Error object, not a string. Only an Error has a name, a message and a record of where it came from.

Custom Error Messages

A good message says what was expected, what arrived, and which item it was about.

A vague message and a helpful message for the same problem

const item = { name: "Notebook", quantity: -2 };

function checkVague(item) {
  if (item.quantity < 1) throw new Error("Invalid input");
}

function checkHelpful(item) {
  if (item.quantity < 1) {
    throw new Error(`Quantity for ${item.name} must be 1 or more, received ${item.quantity}`);
  }
}

for (const check of [checkVague, checkHelpful]) {
  try {
    check(item);
  } catch (error) {
    console.log(error.message);
  }
}

Expected output:

Invalid input
Quantity for Notebook must be 1 or more, received -2

Keep passwords and card numbers out of error messages. Messages end up in logs that other people read.

Error Object

name

The kind of error, like "TypeError". Code can check it to decide what to do.

Two different problems, two different names

const problems = [
  () => null.toFixed(2),
  () => totalPrice * 2,
];

for (const problem of problems) {
  try {
    problem();
  } catch (error) {
    console.log("name:", error.name);
  }
}

Expected output:

name: TypeError
name: ReferenceError

message

The human-readable description. For your own errors, it is the text you passed to new Error().

An error you create yourself, with its name and message

const error = new Error("Payment was declined");

console.log("name:", error.name);
console.log("message:", error.message);

Expected output:

name: Error
message: Payment was declined

Built-in Error Types

Error

The general type. All others are built on it, so instanceof Error is true for every one.

Every built-in error type is also an Error

const general = new Error("Something went wrong");
const typeProblem = new TypeError("Expected a number");

console.log(general instanceof Error);
console.log(typeProblem instanceof Error);
console.log(typeProblem instanceof TypeError);

Expected output:

true
true
true

TypeError

A value is the wrong type: reading from null, or calling something that is not a function. The most common error.

Calling a string as if it were a function

const greeting = "Hello, Ravi";

try {
  greeting();
} catch (error) {
  console.log(error.name + ":", error.message);
}

Expected output:

TypeError: greeting is not a function

ReferenceError

A name that does not exist, usually a spelling or capital-letter mistake.

A variable name with one letter in the wrong case

const cartTotal = 250;

try {
  console.log(carttotal);
} catch (error) {
  console.log(error.name + ":", error.message);
}

Expected output:

ReferenceError: carttotal is not defined

SyntaxError

Text that cannot be read as code or data. From JSON.parse() it happens at run time, so it can be caught.

Reading badly written JSON throws a catchable SyntaxError

try {
  JSON.parse("{name: 'Asha'}");
} catch (error) {
  console.log(error.name);
  console.log(error instanceof SyntaxError);
}

Expected output:

SyntaxError
true
TypeWhat it meansTypical cause
Errora general probleman error you throw yourself
TypeErrora value is the wrong typereading from null, calling a non-function
ReferenceErrora name does not exista spelling mistake
SyntaxErrortext could not be reada missing bracket, or bad JSON

JSON Exception Handling

Text from outside your program can be broken. The JSON Handling lesson covers JSON in full.

Handling JSON.parse() Errors

Wrap every parse of outside text. Handle the SyntaxError you expect, and rethrow anything else (throw error;) so real bugs are not hidden.

safeParse returns a fallback value instead of crashing

function safeParse(text, fallback) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      console.log("Bad JSON, using the fallback.");
      return fallback;
    }
    throw error;
  }
}

const saved = safeParse('{"theme":"dark"}', { theme: "light" });
const broken = safeParse('{"theme":"dark"', { theme: "light" });

console.log(saved.theme);
console.log(broken.theme);

Expected output:

Bad JSON, using the fallback.
dark
light

Error Handling on a Web Page

The form checks the quantity. Bad input throws a clear error; catch shows it; finally turns the button back on.

A form that throws and catches its own errors

const form = document.querySelector("#order");
const result = document.querySelector("#result");
const button = document.querySelector("#submit");

function readQuantity() {
  const qty = Number(document.querySelector("#qty").value);
  if (!Number.isInteger(qty) || qty < 1) {
    throw new RangeError(`Quantity must be a whole number of 1 or more, received ${document.querySelector("#qty").value || "nothing"}`);
  }
  return qty;
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  button.disabled = true;
  try {
    const qty = readQuantity();
    result.textContent = `Order placed for ${qty} item(s).`;
    result.style.color = "green";
  } catch (error) {
    result.textContent = `${error.name}: ${error.message}`;
    result.style.color = "crimson";
  } finally {
    button.disabled = false;
    console.log("finally ran, button enabled again");
  }
});

Set the quantity to 0 or 2.5 and press Place order. You see the RangeError message, and the button still works.

Easy way to remember: try = attempt, catch = rescue, finally = tidy up, throw = raise the alarm.

TL;DR

  • Syntax errors stop everything; runtime errors can be caught; logical errors are silent.
  • try stops at the first throw and jumps to catch (error).
  • finally always runs. Never return from it.
  • throw new Error("clear message"), never a plain string.
  • Check error.name; wrap JSON.parse(); rethrow what you cannot handle.

Try this

In the withdraw example, change withdraw(500, 900) to withdraw(500, 450). Nothing is thrown, catch is skipped, and you see two New balance lines.

Check Yourself

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
An empty catchSilence is safeHandle, report or rethrowA stranger error appears later
throw "failed"Any value worksThrow new Error("failed")error.message is undefined
Too much code in tryIt all still runstry stops at the first throwLater lines are skipped
Expecting try to catch wrong mathsAll mistakes throwLogical errors do notThe wrong total slips through
return inside finallyIt only adds a stepIt replaces the resultThe real error disappears
JSON.parse on outside text, no tryData is always validIt can be brokenThe whole page stops

Quick reference

SyntaxMeaning
try { ... }run code that might fail
catch (error) { ... }run only when try throws, with the error in error
catch { ... }the same, when the error object is not needed
finally { ... }run every time, for clean-up
throw new Error("message")stop and hand an error to the nearest catch
throw new TypeError("message")throw an error that says a value had the wrong type
error.namethe kind of error, such as "TypeError"
error.messagethe description of what went wrong
error instanceof SyntaxErrorcheck which type of error was caught
throw error; inside catchrethrow an error you do not know how to handle

Exercises

What to Remember

  • Errors stop code; exceptions can be caught.
  • try/catch/finally keep the program running and tidy.
  • Throw Error objects with clear messages.

Next: Debugging. Find the cause of an error with the console, breakpoints and stack traces, and fix the common ones.