Errors & Good PracticeExtra· 35 min read

Errors, try/catch & Debugging

Things go wrong — handle errors gracefully and learn to track down bugs.

What you will learn

  • Handle errors with try/catch
  • Read error messages
  • Debug with the console

try / catch

Wrap risky code (like a fetch) in try. If it fails, catch runs instead of crashing the whole script.

try/catch prevents a crash
<p id="out"></p>
<script>
  async function load() {
    try {
      const res = await fetch("https://bad-url-that-fails.example");
      const data = await res.json();
      document.getElementById("out").textContent = "Loaded!";
    } catch (error) {
      document.getElementById("out").textContent = "Something went wrong: could not load data.";
    }
  }
  load();
</script>
Live preview

Here is the flow when something fails:

  1. JavaScript runs the code inside try line by line.
  2. The fetch here points to a fake, broken URL, so it throws an error.
  3. The moment an error is thrown, the rest of the try block is skipped (so "Loaded!" never runs).
  4. Control jumps to catch (error), where we show a friendly message instead of crashing.

Note: Output: Something went wrong: could not load data. (Without try/catch, the broken fetch would have thrown an uncaught error and stopped the script.)

Debugging tips

  • Open the Console (F12) — errors appear there in red, with the line number.
  • Sprinkle console.log(value) to check what variables actually contain.
  • Read the error message — it usually tells you exactly what and where.

Tip: Every developer hits errors constantly — they are normal, not failure. Reading the message and console.log-ing values are the two skills that fix 90% of bugs.

Q. Which block runs if the code inside try fails?

Answer: catch runs when an error is thrown in the try block, letting you handle it gracefully instead of crashing.

✍️ Practice

  1. Wrap a fetch in try/catch and show a friendly message on failure.
  2. Cause a deliberate error and read it in the console.

🏠 Homework

  1. Add error handling to your earlier fetch project.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →