JavaScript Errors
JavaScript errors occur when the engine encounters invalid code or an unexpected condition. Understanding errors helps you debug code and improve stability.
Key Topics
- Types of Errors
- Handling Errors with try...catch
- Throwing Custom Errors
- JavaScript Usage in DOM
- Key Takeaways
Types of Errors
Common error types include SyntaxError, ReferenceError, TypeError, and RangeError. Each indicates a different kind of problem in your code.
Handling Errors with try...catch
Use try...catch
to handle runtime errors gracefully, preventing the script from terminating unexpectedly.
try {
let result = someUndefinedFunction();
} catch (error) {
console.log("An error occurred: " + error.message);
}
Output
> An error occurred: someUndefinedFunction is not defined
Explanation: The try block throws a ReferenceError, caught and handled in catch.
Throwing Custom Errors
Use throw
to create custom errors and handle specific conditions in your code.
JavaScript Usage in DOM
Gracefully handle errors when fetching data or updating the DOM. Display user-friendly messages rather than letting the script fail silently.
<!DOCTYPE html>
<html>
<head><title>Errors in DOM</title></head>
<body>
<h1>Error Handling Demo</h1>
<button onclick="runCode()">Run</button>
<p id="output"></p>
<script>
function runCode() {
try {
let x = nonExistentVar;
} catch (e) {
document.getElementById("output").textContent = "Error: " + e.message;
}
}
</script>
</body>
</html>
Key Takeaways
- Error Types: SyntaxError, ReferenceError, TypeError, etc.
- Handling: Use try...catch for graceful error management.
- Throw: Create custom errors for specific conditions.
- DOM Integration: Show friendly messages when issues occur, instead of failing silently.