JavaScript Errors
Understanding and handling errors in JavaScript
โ ๏ธ What are JavaScript Errors?
Errors are problems in your code that prevent it from running correctly. JavaScript provides ways to catch and handle these errors gracefully instead of crashing your program.
// This will cause an error
try {
let result = someUndefinedFunction();
} catch (error) {
console.log("Oops! Something went wrong:", error.message);
}
// Program continues running!
Console Output:
Oops! Something went wrong: someUndefinedFunction is not defined
Common Error Types
Syntax Error
Wrong code structure
// Missing closing bracket
if (true {
console.log("Error!");
}
Reference Error
Using undefined variables
// Variable doesn't exist
console.log(undefinedVariable);
// ReferenceError
Type Error
Wrong data type usage
// Calling non-function
let number = 5;
number(); // TypeError
Range Error
Value outside valid range
// Invalid array length
let arr = new Array(-1);
// RangeError
๐น Try-Catch-Finally
Handle errors gracefully with try-catch blocks:
// Basic error handling
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
let result = a / b;
console.log(`${a} รท ${b} = ${result}`);
return result;
} catch (error) {
console.log("Error occurred:", error.message);
return null;
} finally {
console.log("Division operation completed");
}
}
// Test the function
divideNumbers(10, 2); // Success
divideNumbers(10, 0); // Error
Console Output:
10 รท 2 = 5
Division operation completed
Error occurred: Cannot divide by zero!
Division operation completed
Division operation completed
Error occurred: Cannot divide by zero!
Division operation completed
๐น Throwing Custom Errors
Create your own errors with meaningful messages:
// Custom error handling for user age
function validateAge(age) {
try {
if (typeof age !== 'number') {
throw new TypeError("Age must be a number");
}
if (age < 0) {
throw new RangeError("Age cannot be negative");
}
if (age > 150) {
throw new RangeError("Age seems unrealistic");
}
console.log(`Valid age: ${age}`);
return true;
} catch (error) {
console.log(`Validation failed: ${error.name} - ${error.message}`);
return false;
}
}
// Test different inputs
validateAge(25); // Valid
validateAge("thirty"); // TypeError
validateAge(-5); // RangeError
validateAge(200); // RangeError
Console Output:
Valid age: 25
Validation failed: TypeError - Age must be a number
Validation failed: RangeError - Age cannot be negative
Validation failed: RangeError - Age seems unrealistic
Validation failed: TypeError - Age must be a number
Validation failed: RangeError - Age cannot be negative
Validation failed: RangeError - Age seems unrealistic
๐น Error Object Properties
Error objects contain useful information:
// Exploring error properties
try {
// This will cause a ReferenceError
console.log(nonExistentVariable);
} catch (error) {
console.log("Error Name:", error.name);
console.log("Error Message:", error.message);
console.log("Error Stack:", error.stack);
// Check error type
if (error instanceof ReferenceError) {
console.log("This is a Reference Error!");
}
}
Console Output:
Error Name: ReferenceError
Error Message: nonExistentVariable is not defined
Error Stack: ReferenceError: nonExistentVariable is not defined...
This is a Reference Error!
Error Message: nonExistentVariable is not defined
Error Stack: ReferenceError: nonExistentVariable is not defined...
This is a Reference Error!
๐น Practical Error Handling
Real-world example with JSON parsing:
// Safe JSON parsing function
function parseJSON(jsonString) {
try {
let data = JSON.parse(jsonString);
console.log("Successfully parsed:", data);
return data;
} catch (error) {
if (error instanceof SyntaxError) {
console.log("Invalid JSON format:", error.message);
} else {
console.log("Unexpected error:", error.message);
}
return null;
}
}
// Test with different inputs
let validJSON = '{"name": "John", "age": 30}';
let invalidJSON = '{"name": "John", "age":}'; // Missing value
parseJSON(validJSON); // Success
parseJSON(invalidJSON); // SyntaxError
parseJSON(null); // TypeError
Console Output:
Successfully parsed: {name: "John", age: 30}
Invalid JSON format: Unexpected token } in JSON at position 20
Unexpected error: Cannot read property 'charAt' of null
Invalid JSON format: Unexpected token } in JSON at position 20
Unexpected error: Cannot read property 'charAt' of null
๐น Best Practices
Error Handling Tips:
- Be Specific: Catch specific error types when possible
- Meaningful Messages: Provide clear error messages
- Don't Ignore: Always handle or log errors
- Use Finally: For cleanup code that must run
- Validate Input: Check data before processing
// Good error handling example
function processUserData(userData) {
try {
// Validate input
if (!userData) {
throw new Error("User data is required");
}
// Process data
let result = userData.name.toUpperCase();
console.log("Processed:", result);
return result;
} catch (error) {
// Log for debugging
console.error("Processing failed:", error.message);
// Return safe default
return "UNKNOWN USER";
}
}