agyanadda@gmail.com

JS Error Handling

Modern JS and Best Practices 1 min read Updated Dec 1, 2026 Topic 35 of 38

Errors stop your script. Handle them so the page keeps working and the user sees a helpful message.

try {
  const data = JSON.parse(text);
} catch (err) {
  console.error(err.message);
} finally {
  // always runs
}

throw your own errors

if (age < 0) throw new Error('Age cannot be negative');

Common error types

Error Cause
ReferenceError using a variable that does not exist
TypeError wrong type, e.g. calling null.length
SyntaxError invalid code or invalid JSON
RangeError number out of allowed range

Debugging tips

  • Read the error message and line number in the console
  • Use console.log to check values
  • Use the Sources tab breakpoints, or the debugger; statement

Example

Example — Safe JSON parsing HTML
<textarea id="json" rows="3" cols="40">{"name": "Asha", "age": 20}</textarea><br>
<button id="parse">Parse</button>
<pre id="out"></pre>

<script>
  document.getElementById('parse').onclick = () => {
    const out = document.getElementById('out');
    try {
      const obj = JSON.parse(document.getElementById('json').value);
      if (obj.age < 0) throw new Error('Age cannot be negative');
      out.textContent = 'OK: ' + obj.name + ', ' + obj.age;
      out.style.color = 'green';
    } catch (err) {
      out.textContent = err.name + ': ' + err.message;
      out.style.color = 'crimson';
    }
  };
</script>

Try removing a quote or setting age to -5, then press Parse.

Try it Now »

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which block always runs, error or not?

Exercise 2 Fill in the Blank

Use the ___ keyword to create your own error.

Exercise 3 True / False

Calling a method on null causes a TypeError.

Frequently Asked Questions

No. Use it where errors are expected, such as parsing data, network requests or user input.