JavaScript Errors

try, catch, finally and throw.

✍️ 3 exercises + code challenge in this lesson

When something goes wrong, JavaScript throws an error and stops. You can handle errors gracefully:

  • try { }: code that might fail.
  • catch (error) { }: runs if an error is thrown; error.message describes it.
  • finally { }: always runs, error or not.
  • throw new Error("message"): create your own errors.

Built-in error types include ReferenceError, TypeError, SyntaxError and RangeError.

Key Takeaways: JavaScript Errors

Mastering JavaScript Errors helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Errors Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
function withdraw(balance, amount) {
  if (amount > balance) {
    throw new Error("Insufficient balance");
  }
  return balance - amount;
}

try {
  log("New balance:", withdraw(5000, 1500));
  log("New balance:", withdraw(5000, 9000));
} catch (error) {
  log("Error:", error.message);
} finally {
  log("Transaction finished.");
}

try {
  undefinedFunction();
} catch (e) {
  log(e.name + ":", e.message);
}
</script>
Free sign-in required · Google login available

JavaScript Errors Practice Exercises

Check what you learned in “JavaScript Errors”.

/ 3 solved
Fill in the blank

Catch errors thrown in the try block.

try {
  riskyCode();
}  (error) {
  log(error.message);
}
✓ Correct! Not quite. Try again.
Multiple choice

Which block always runs, error or not?

✓ Correct! Not quite. Try again.
Code challenge

Call JSON.parse on invalid text inside try/catch and log "Invalid JSON" when it fails.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services