Errors & Good Practice›Extra· 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.
<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:
- JavaScript runs the code inside
tryline by line. - The
fetchhere points to a fake, broken URL, so it throws an error. - The moment an error is thrown, the rest of the
tryblock is skipped (so "Loaded!" never runs). - 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
- Wrap a fetch in
try/catchand show a friendly message on failure. - Cause a deliberate error and read it in the console.
🏠 Homework
- Add error handling to your earlier fetch project.