# Error and Exception Handling

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Error Handling
Source: https://www.devtutorials.ai/learn/javascript/error-handling/error-and-exception-handling

> 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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="Three orders move along a belt. The middle one is broken. Without try it stops the belt; with try it drops into a catch box and the belt keeps going." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="20" y="40" width="380" height="60" rx="10" fill="#eff6ff" stroke="#2563eb" strokeDasharray="6 4" />
    <text x="30" y="34" fontSize="12" fill="#1e40af">try</text>
    <rect x="430" y="40" width="110" height="60" rx="10" fill="#fef3c7" stroke="#d97706" />
    <text x="485" y="75" textAnchor="middle" fontSize="12" fill="#92400e">catch</text>
    <rect y="55" width="60" height="30" rx="6" fill="#bbf7d0" stroke="#16a34a"><animate attributeName="x" values="30;330" dur="3s" repeatCount="indefinite" /></rect>
    <rect y="55" width="60" height="30" rx="6" fill="#fecaca" stroke="#dc2626"><animate attributeName="x" values="130;200;455;455" keyTimes="0;0.3;0.6;1" dur="3s" repeatCount="indefinite" /></rect>
    <rect y="55" width="60" height="30" rx="6" fill="#bbf7d0" stroke="#16a34a"><animate attributeName="x" values="230;400" dur="3s" repeatCount="indefinite" /></rect>
    <rect x="20" y="118" width="520" height="34" rx="8" fill="#f1f5f9" stroke="#94a3b8" />
    <text x="280" y="140" textAnchor="middle" fontSize="12" fill="#334155">finally: runs every time (clean-up)</text>
  </svg>
  <figcaption>The broken order drops into catch. The others keep moving.</figcaption>
</figure>

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.

```js runnable expect-error title="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.

```js runnable expect-error title="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.

```js runnable expect-error title="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.

```js runnable expect-error title="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`.

```js runnable title="Three test scores, and an average that is far too high"
const average = 80 + 90 + 70 / 3;

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

Expected output:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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);
}
```

| Kind | When it shows up | Becomes an exception? |
|---|---|---|
| Syntax error | before the program starts | No, the program never runs |
| Runtime error | while a line runs | Yes, it can be caught |
| Logical error | never reported | No, nothing is thrown |

## Exception Handling

### `try`

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

```js runnable title="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:

```text
[
  "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.

```js runnable title="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:

```text
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".

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
name: TypeError
name: ReferenceError
```

### `message`

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

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
TypeError: greeting is not a function
```

### `ReferenceError`

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

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
SyntaxError
true
```

| Type | What it means | Typical cause |
|---|---|---|
| `Error` | a general problem | an error you throw yourself |
| `TypeError` | a value is the wrong type | reading from `null`, calling a non-function |
| `ReferenceError` | a name does not exist | a spelling mistake |
| `SyntaxError` | text could not be read | a missing bracket, or bad JSON |

## JSON Exception Handling

Text from outside your program can be broken. The [JSON Handling](/learn/javascript/data-handling/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.

```js runnable title="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:

```text
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.

```js runnable preview="order-form" title="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

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| An empty `catch` | Silence is safe | Handle, report or rethrow | A stranger error appears later |
| `throw "failed"` | Any value works | Throw `new Error("failed")` | `error.message` is `undefined` |
| Too much code in `try` | It all still runs | `try` stops at the first throw | Later lines are skipped |
| Expecting `try` to catch wrong maths | All mistakes throw | Logical errors do not | The wrong total slips through |
| `return` inside `finally` | It only adds a step | It replaces the result | The real error disappears |
| `JSON.parse` on outside text, no `try` | Data is always valid | It can be broken | The whole page stops |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `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.name` | the kind of error, such as `"TypeError"` |
| `error.message` | the description of what went wrong |
| `error instanceof SyntaxError` | check which type of error was caught |
| `throw error;` inside `catch` | rethrow an error you do not know how to handle |

</div>

## 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.
