JavaScript Error Handling
Master try/catch, error types, custom errors, and debugging strategies with interactive code exercises.
Category: Programming
·
v1.0.0
Step 1 of 6
Step 1: What are Errors?
When JavaScript encounters a problem it cannot recover from, it creates an Error object and throws it. Errors halt execution unless they are caught.
There are two broad categories:
- Syntax Errors — detected at parse time before any code runs (e.g., missing brackets)
- Runtime Errors — occur while the program is executing (e.g., calling an undefined function)
JavaScript has several built-in error types:
TypeError
Occurs when a value is not the expected type.
null.toString(); // TypeError: Cannot read properties of null
(42).toUpperCase(); // TypeError: not a function
ReferenceError
Occurs when referencing a variable that doesn't exist.
console.log(myVar); // ReferenceError: myVar is not defined
undeclaredFn(); // ReferenceError: undeclaredFn is not defined
SyntaxError
Occurs when code has invalid syntax (caught at parse time, or via eval/JSON.parse).
JSON.parse("{bad}"); // SyntaxError: Unexpected token b
eval("if("); // SyntaxError: Unexpected end of input
RangeError
Occurs when a value is outside its allowed range.
new Array(-1); // RangeError: Invalid array length
(1.5).toFixed(200); // RangeError: toFixed() digits argument
URIError
Occurs when URI encoding/decoding functions receive invalid input.
decodeURIComponent('%'); // URIError: URI malformed
Key Terms
throw
Manually trigger an error: throw new Error("message")
catch
Intercept a thrown error and handle it gracefully
stack trace
The chain of function calls that led to the error
error.message
Human-readable description of what went wrong
error.name
The type of error (e.g., "TypeError", "RangeError")
About This Lab
Robust error handling separates production-quality code from fragile scripts. In this lab, you'll learn about JavaScript's built-in error types, use try/catch/finally blocks, create custom error classes, handle async errors, and practice defensive programming — all with live code editors that let you trigger and catch errors in real time.
How It Works
- Read each step's explanation of error handling concepts
- Run code that throws errors and catch them
- Experiment with different error types
- Build custom error handlers
- Complete the quiz to test your understanding