TalentJR

🟨 JavaScript tutorial for beginners · Class 9 · Lesson 5 of 18 · Free

Error Handling – try, catch, throw and finally in JavaScript

⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in

In this lesson you will

  • Catch errors with try/catch and read an error's name and message
  • Throw your own errors to stop bad data early
  • Use finally and handle fetch errors with async/await

A railway booking site gets a wrong date, a lost internet connection and a server hiccup — all in one minute. It does not show a blank white page. It says "Please check the date" or "Try again". In this lesson you will learn how JavaScript catches problems and keeps going.

How does try and catch work in JavaScript?

When JavaScript hits an error it cannot handle, it stops the whole program. Every line after it is skipped.

Put risky code inside `try { }`. If an error happens there, JavaScript jumps straight to `catch (err) { }` and the program carries on after it.

The caught error is an object. `err.name` says what kind of error it is, and `err.message` says what went wrong.

🎬 How JavaScript thinks — step 1 of 8JavaScript is about to run line 1
▶const text = '{"name": "Asha", "marks": 92';
2
3try {
4 console.log("Reading the data…");
5 const student = JSON.parse(text);
6 console.log("Name:", student.name);
7} catch (err) {
8 console.log("Could not read it!");
9 console.log(err.name);
10}
11console.log("The program is still running ✅");
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
Reading the data…
Could not read it!
SyntaxError
The program is still running ✅

💡 Try it: add the missing } at the end of the text and run again. Now catch is skipped.

What are the common error types in JavaScript?

`ReferenceError`: you used a name that does not exist, often a typo. `TypeError`: you did something a value cannot do, like reading a property of `undefined`.

`SyntaxError`: the code or the JSON text breaks the grammar rules. `RangeError`: a number is outside the allowed range.

Knowing the name tells you where to look. Here each risky job is a small function, and one loop tries them all.

🟨 JavaScript — you can edit this code
Console output
ReferenceError: totl is not defined
TypeError: Cannot read properties of undefined (reading 'length')
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
RangeError: toFixed() digits argument must be between 0 and 100

💡 A SyntaxError in your own code (not in JSON text) cannot be caught — the program does not even start.

How do I throw my own error in JavaScript?

Sometimes the code runs fine, but the data is wrong: marks of 120, or a negative ticket count. JavaScript will not complain, so you must.

`throw new Error("message")` stops the function right there and sends the error up to the nearest `catch`.

Check bad data as early as possible. It is much easier to fix a problem where it starts.

🎬 How JavaScript thinks — step 1 of 20JavaScript is about to run line 10
1function result(marks) {
2 if (typeof marks !== "number") {
3 throw new Error("Marks must be a number");
4 }
5 if (marks < 0 || marks > 100) {
6 throw new Error(`Marks ${marks} are out of range`);
7 }
8 return marks >= 35 ? "Pass" : "Fail";
9}
▶for (const m of [95, 120, "ninety"]) {
11 try {
12 console.log(m, "→", result(m));
13 } catch (err) {
14 console.log("⚠️", err.message);
15 }
16}
📦 Variables (memory boxes)
m
95
🖥️ Output
▌
✏️ Change this code and run it yourself
🟨 JavaScript — you can edit this code
Console output
95 → Pass
⚠️ Marks 120 are out of range
⚠️ Marks must be a number

💡 Try it: add 75 to the list. Then try -5.

What does finally do in a try catch?

`finally { }` runs at the end every time — after `try` if it worked, after `catch` if it failed.

Use it for clean-up that must always happen: hide the "Loading…" text, close the counter, turn off a spinner.

It even runs if the `try` block uses `return` (see the second predict question below).

🟨 JavaScript — you can edit this code
Console output
Printer ON 🖨️
Ticket printed for seat 14
Printer OFF
Printer ON 🖨️
Problem: Seat 99 does not exist
Printer OFF

How do I handle fetch errors with async and await in JavaScript?

In Lesson 4 you saw that `fetch` does not fail on 404 or 500. A neat trick is to check `response.ok` and `throw` yourself. Then one `catch` handles every kind of failure.

If the internet is off, `fetch` itself throws a TypeError. The same `catch` handles that too.

We use the TalentJR practice API again (made-up data). Its `/broken` address always fails, for practice.

🟨 JavaScript — you can edit this code
Console output
✅ /quotes/1 ["id", "text", "topic"]
❌ /broken Server said 500
❌ /students/42 Server said 404

💡 Object.keys(data) lists the property names, a quick way to peek at what arrived.

How do I show a friendly error message on a web page?

Users should never see `TypeError: Cannot read properties…`. Catch the error and show a short, kind message on the page instead.

Type marks into the box and click Check. Try 85, 150 and some letters.

The same idea as `result` above throws errors. The click handler catches them and paints the message red.

🟨 JavaScript — you can edit this code
📄 HTML of the page (tap to see / edit)
🖥️ Your web page — try clicking it
Console output
Marks must be between 0 and 100.

🤔 Predict the output

Think like JavaScript: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

try {
  console.log("A");
  throw new Error("B");
  console.log("C");
} catch (err) {
  console.log(err.message);
}

Question 2. What does this print?

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

Question 3. What does this print?

try {
  const team = null;
  console.log(team.length);
} catch (err) {
  console.log(err.name);
}

🧩 Your challenge

Write a bill splitter for a class trip. splitBill(total, friends) must throw an Error with a clear message if total is not a positive number, or if friends is not a whole number of at least 1 (use Number.isInteger). Otherwise return each share rounded to 2 decimals with toFixed(2). Run it for the four test cases with try/catch around each, and print "Done checking bills" after the loop. Expected output: ₹1200 / 4 = ₹300.00 each ₹1000 / 3 = ₹333.33 each ❌ Friends must be a whole number, at least 1 ❌ Total must be a positive number Done checking bills

Expected output in the console:
₹1200 / 4 = ₹300.00 each
₹1000 / 3 = ₹333.33 each
❌ Friends must be a whole number, at least 1
❌ Total must be a positive number
Done checking bills
🟨 JavaScript — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

try {
  const total = 40 + 60;
} catch (err) {
  console.log(err.message);
}
console.log("Total:", total);

ReferenceError: total is not defined

✅ Right

let total = 0;
try {
  total = 40 + 60;
} catch (err) {
  console.log(err.message);
}
console.log("Total:", total);

A const or let made inside { } only lives inside those braces. Declare the variable before the try if you need it after.

❌ Wrong

function checkAge(age) {
  if (age < 0) {
    throw "Age cannot be negative";
  }
}
try {
  checkAge(-3);
} catch (err) {
  console.log("Problem:", err.message);
}

No error, but it prints "Problem: undefined" — a plain string has no .message property.

✅ Right

function checkAge(age) {
  if (age < 0) {
    throw new Error("Age cannot be negative");
  }
}
try {
  checkAge(-3);
} catch (err) {
  console.log("Problem:", err.message);
}

You can throw any value, but only Error objects have .message (and .name). Always throw new Error(...).

❌ Wrong

async function loadQuote() {
  const response = await fetch("https://api.talentjr.in/api/v1/practice/broken");
  if (!response.ok) {
    throw new Error(`Server said ${response.status}`);
  }
}
try {
  loadQuote();
} catch (err) {
  console.log("Caught:", err.message);
}

Error: Server said 500

✅ Right

async function loadQuote() {
  const response = await fetch("https://api.talentjr.in/api/v1/practice/broken");
  if (!response.ok) {
    throw new Error(`Server said ${response.status}`);
  }
}
try {
  await loadQuote();
} catch (err) {
  console.log("Caught:", err.message);
}

Without await, the try block finishes before the fetch fails, so catch never sees the error. await the async function inside try.

📌 Remember

  • An uncaught error stops the program; try/catch catches it and lets the program carry on.
  • err.name tells the kind (ReferenceError, TypeError, SyntaxError, RangeError); err.message tells what went wrong.
  • throw new Error("…") stops bad data early and sends it to the nearest catch.
  • finally always runs — use it for clean-up.
  • With fetch, check response.ok and throw, then await inside try so one catch handles every failure.

Finished the quiz and the challenge?

Questions students ask

When should I use try catch in JavaScript?

Use it around code that can fail for reasons outside your control: reading JSON, fetching data, or reading what a user typed. Do not wrap every line — a bug in your own code should be fixed, not hidden.

What is the difference between throw and return?

return hands a normal answer back to the caller. throw says "something is wrong" and skips all code until the nearest catch, even across several functions.

Why does my try catch not catch an error from fetch?

Usually because the async function was called without await. Then the try block ends before the error happens. Write await inside the try, or add .catch(...) to the Promise.

Can I make my own error types?

Yes. Using Lesson 1, write class MarksError extends Error { } and throw new MarksError("…"). In catch you can check err instanceof MarksError to treat it differently.