JavaScript Error Handling
Master try/catch, error types, custom errors, and debugging strategies with interactive code exercises.
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
How It Works
- 1 Read each step's explanation of error handling concepts
- 2 Run code that throws errors and catch them
- 3 Experiment with different error types
- 4 Build custom error handlers
- 5 Complete the quiz to test your understanding
More Labs in Programming
Git Fundamentals
ProgrammingLearn the core Git workflow — staging, committing, branching, and merging through an interactive terminal simulator.
JavaScript DOM Manipulation
ProgrammingLearn to select, modify, and create HTML elements dynamically using JavaScript DOM methods.
Linux Command Line
ProgrammingNavigate the file system, manage files, and learn essential Linux commands in a simulated terminal.