SA-21/06, C-11, Asapur, Varanasi, UP support@kamaldnp.com +91 8318013442
Lesson 24 of 30

JavaScript Errors — try, catch, finally

5 min read · Free · No login needed

Every program has mistakes. A variable is spelled wrong, a number is divided by nothing, a server does not answer. In JavaScript, a mistake like that is called an error, and by default it stops the whole script — everything after the error never runs. That is why a small typo can blank out an entire page. The fix is to catch the error before it reaches the top: try, catch and finally.

Diagram — see how it fits together
Diagram: JavaScript Errors — try, catch, finally

Think of a chai shop order. You try to make the chai (the risky step). If the milk is finished, you catch the problem and serve black tea instead (the backup plan). And finally, whether the order worked or not, you clean the counter (the tidy-up). The shop never closes because of one missing item — and your page should not break because of one bad value.

try, catch, finally — the three parts

try {
  // risky code — if it throws, jump to catch
  let total = price * qty;
} catch (error) {
  // backup plan — error.message tells you what went wrong
  console.log("Something went wrong: " + error.message);
} finally {
  // always runs — tidy up here
  console.log("Done.");
}

The try block holds the risky code. If anything inside it throws an error, JavaScript jumps straight to the catch block and skips the rest of try. The catch block receives the error as an object, and error.message holds a short description. The finally block runs no matter what — error or no error — so it is the right place for clean-up, like closing a loading message.

Note: A try block without catch is allowed only if it has finally. But try with finally and no catch does not stop the error — it only runs the tidy-up, then the error continues. To actually handle the error, you need catch.

throw — making your own errors

Sometimes the code runs fine but the value is wrong — a negative age, an empty name, a quantity of zero. JavaScript does not know that is an error, so you throw one yourself:

function checkAge(age) {
  if (age < 0) {
    throw new Error("Age cannot be negative.");
  }
  return "Age is fine.";
}

throw new Error("...") stops the function immediately and jumps to the nearest catch. This turns a silent wrong value into a loud, visible problem — much easier to find and fix than a bill that quietly comes out wrong.

Common errors — learn to read them

  • ReferenceError: x is not defined — you used a variable that does not exist, usually a spelling mistake. Check the name letter by letter.
  • TypeError: Cannot read properties of null — you tried to use something that is null, often because getElementById could not find the element. Check the id in the HTML.
  • SyntaxError: Unexpected token — the code itself is written wrong, like a missing bracket. The browser points at the line — start there.
  • RangeError: Maximum call stack size exceeded — a function calls itself forever. Check that your recursion or loop has a way out.

Read the first line of the error message, not the whole stack. The first line usually tells you the type and the place — that is enough to find the bug in most cases.

Tip: Remember it like this: try the risky step, catch the fall, finally tidy up. Wrap only the risky part in try — wrapping your whole program hides the real mistake and makes debugging harder.

Common mistakes

  • Wrapping everything in one giant try — you lose track of where the error actually came from. Keep the try block small.
  • An empty catch block — the error is swallowed silently and the bug becomes invisible. At least log error.message.
  • Forgetting that try only catches errors that happen inside it — an error in a timer or a promise needs its own handling.
  • Using throw "some string" instead of throw new Error("...") — a string has no stack trace, so you cannot find where it came from.

Remember

  • try holds the risky code, catch holds the backup plan, finally always runs.
  • throw new Error("...") makes your own error when a value is wrong.
  • Read the first line of the error — it usually names the type and the place.
  • Try the risky step, catch the fall, finally tidy up.

Example explained

  • let age = Number(document.getElementById("age").value); — reads the age box and converts the string to a number.
  • if (isNaN(age)) { throw new Error("Please type a number."); } — if the input is not a number, we throw our own error instead of continuing with a broken value.
  • if (age < 0) { throw new Error("Age cannot be negative."); } — a second check: a negative age is impossible, so it is an error too.
  • catch (error) { ... error.message ... } — whichever error was thrown, the message is shown on the page in red. The page never breaks.
  • finally { document.getElementById("age").value = ""; } — the input box is cleared whether the check passed or failed, so the next try starts clean.

Example

Example
<!DOCTYPE html>
<html>
<head>
<title>Age Check — try and catch</title>
<style>
body { font-family: Verdana, sans-serif; background-color: #fff8e1; }
h1 { color: #b45309; text-align: center; }
.card { background-color: white; border: 2px solid #f59e0b; padding: 16px; width: 340px; margin: 20px auto; }
button { background-color: #b45309; color: white; border: none; padding: 10px 18px; font-size: 16px; }
#out { font-weight: bold; }
</style>
</head>
<body>

<h1>Age Check</h1>
<div class="card">
<p>Your age: <input id="age" type="text" value="25"></p>
<p><button onclick="checkAge()">Check my age</button></p>
<p id="out">Type your age and click the button.</p>
<p>Try it: type -5, or type "abc" — the page shows the error instead of breaking.</p>
</div>

<script>
function checkAge() {
  let out = document.getElementById("out");
  try {
    let age = Number(document.getElementById("age").value);
    if (isNaN(age)) { throw new Error("Please type a number."); }
    if (age < 0) { throw new Error("Age cannot be negative."); }
    out.style.color = "green";
    out.textContent = "Your age is " + age + ". All good!";
  } catch (error) {
    out.style.color = "red";
    out.textContent = "Error: " + error.message;
  } finally {
    document.getElementById("age").value = "";
  }
}
</script>

</body>
</html>

Output

Output — how it looks in the browser
Output of JavaScript Errors — try, catch, finally

Try it yourself — live editor

Change the code below and press Run to see the result instantly. No file to save, no login needed.

Result

Why learn this yourself — and not just ask AI?

AI can write code for you, but it cannot think for you. When you learn HTML yourself, your brain builds the real skill: you understand why a page looks the way it does, you can fix it when it breaks, and you can answer it in an exam or an interview without help. That is the skill that gets you a job — not a copied answer.

Get certified — just ₹10

Finish all 30 lessons, pass the test (80%), pay ₹10 and get your certificate.

Take the test

Prefer watching? Video courses teach the same topics step by step.

Go further with a full course

Free tutorials teach you the basics. Our paid courses add live projects, mentorship and a certificate.

Ethical Hacking & Cyber Security Workshop
View
Summer Industrial Training in MERN Stack 2026
₹3,000
View
WordPress Website Development Course (10 Days)
₹399
View
Browse all courses
JavaScript — Lessons
1. JavaScript Introduction 2. JavaScript Where To 3. JavaScript Output 4. JavaScript Syntax 5. JavaScript Comments 6. JavaScript Variables 7. JavaScript Operators 8. JavaScript Data Types 9. JavaScript Functions 10. JavaScript Objects 11. JavaScript Scope 12. JavaScript Events 13. JavaScript Strings 14. JavaScript Numbers 15. JavaScript Arrays 16. JavaScript Array Methods 17. JavaScript Dates 18. JavaScript Math 19. JavaScript Conditions 20. JavaScript Switch 21. JavaScript For Loops 22. JavaScript While Loops 23. JavaScript Type Conversion 24. JavaScript Errors — try, catch, finally 25. JavaScript JSON 26. JavaScript Arrow Functions 27. JavaScript Classes 28. JavaScript Promises and async/await 29. JavaScript and the DOM 30. JavaScript Form Validation
Final Test — Certificate ₹10

🤖 KAMALDNP AI Assistant

Ask about courses, website & more

Hi! I'm KAMALDNP AI Assistant. Ask me about our courses, website features, or anything else! 😊
Please wait 5s...
🛡️ 7-Day Money-Back Guarantee
🤖 KAMALDNP Assistant ✕

Request human callback:

🔐 Login Required
✕

Download karne ke liye login karo. Login ke baad yahi page pe rahoge!

Naya ho? Register karo →