JavaScript - Errors, try/catch, and Error Handling
Overview
Estimated time: 10–15 minutes
JavaScript provides structured error handling with try
, catch
, finally
, and the Error
object. Mastering these is essential for robust, user-friendly applications.
Learning Objectives
- Understand JavaScript's error types and the Error object
- Use
try/catch/finally
for error handling - Throw and catch custom errors
- Best practices for error management
Prerequisites
Explanation
JavaScript errors can be runtime (e.g., ReferenceError
, TypeError
) or custom (thrown by your code). Use try/catch
to handle exceptions and prevent crashes.
Syntax
try {
// code that may throw
} catch (err) {
// handle error
} finally {
// always runs
}
Throwing Custom Errors
function divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.error(e.message); // Division by zero
}
Common Pitfalls
- Not all errors can be caught (e.g., syntax errors, some async errors)
- Swallowing errors without logging or user feedback
- Using
throw 'string'
instead ofthrow new Error()
Summary
Use try/catch
to handle errors gracefully. Always provide meaningful error messages and avoid hiding problems from users or developers.