Managing Errors Gracefully
Error handling allows your program to gracefully handle unexpected situations instead of crashing or showing cryptic error messages to users.
JavaScript provides try/catch/finally blocks to catch and handle errors, and you can create custom error types for specific situations.
Proper error handling improves user experience, helps with debugging, and makes your applications more robust and production-ready.
// Basic try/catch
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
}
// try/catch/finally
try {
const data = JSON.parse(userInput);
processData(data);
} catch (error) {
console.error('Error processing data:', error);
showErrorMessage('Invalid data format');
} finally {
console.log('Cleanup code runs regardless of error');
hideLoadingSpinner();
}
// Throwing custom errors
function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero!');
}
return a / b;
}
// Custom error types
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
function validateEmail(email) {
if (!email.includes('@')) {
throw new ValidationError('Invalid email format');
}
return true;
}
try {
validateEmail('notanemail');
} catch (error) {
if (error instanceof ValidationError) {
console.log('Validation failed:', error.message);
} else {
console.log('Unknown error:', error);
}
}
- try block - Code that might throw an error
- catch block - Handles errors if they occur
- finally block - Runs regardless of error (cleanup code)
- throw - Manually throw an error
- Error object - Built-in object with name and message properties
- Custom Errors - Extend Error class for specific error types
- error.stack - Stack trace showing where error occurred
- Multiple catches - Handle different error types differently
Try Error Handling
<div class="error-demo">
<h3>Error Handling Examples</h3>
<div class="example">
<h4>1. Try/Catch with JSON</h4>
<textarea id="jsonInput" rows="3">{"name": "Valid JSON"}</textarea>
<button id="parseBtn">Parse JSON</button>
<div id="parseResult"></div>
</div>
<div class="example">
<h4>2. Custom Error - Division Calculator</h4>
<input type="number" id="num1" placeholder="Numerator" value="10">
<input type="number" id="num2" placeholder="Denominator" value="2">
<button id="divideBtn">Divide</button>
<div id="divideResult"></div>
</div>
<div class="example">
<h4>3. Form Validation with Custom Errors</h4>
<input type="text" id="emailInput" placeholder="Enter email">
<input type="number" id="ageInput" placeholder="Age (13-120)">
<button id="validateBtn">Validate</button>
<div id="validateResult"></div>
</div>
</div>
Note: Don't Swallow Errors: Always log or handle errors appropriately - silent failures make debugging very difficult.
Note: User-Friendly Messages: Show clear, helpful error messages to users while logging technical details for developers.
Note: Finally Block: Use finally for cleanup code that must run (closing connections, hiding loaders) regardless of errors.