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.logto 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 »