JavaScript Tutorial in Hindi #37 | Error Handling & Debugging Techniques
✅ 1. What is Error Handling in JavaScript?
- Error handling is the process of detecting and managing errors that occur while your code runs.
- It helps avoid crashing the program and provides meaningful feedback to users or developers.
- Allows graceful recovery or alternative actions when something goes wrong.
✅ 2. Types of Errors in JavaScript
| Error TypeDescriptionExample | ||
| Syntax Error | Code that violates JavaScript grammar rules | Missing a closing bracket { |
| Reference Error | Accessing a variable that doesn’t exist | Using an undefined variable |
| Type Error | Performing an operation on incompatible type | Calling a number like a function |
| Range Error | Number out of allowable range | Creating array with negative length |
| Custom Errors | Programmer-defined errors using throw | throw new Error('Invalid input') |
✅ 3. The try-catch Block in JavaScript
- Used to catch runtime errors and handle them without stopping the script.
tryblock contains the code that may throw an error.catchblock handles the error.- Optional
finallyblock runs code regardless of error.
js
CopyEdit
try {
// Code that might throw an error
let result = riskyFunction();
console.log(result);
} catch (error) {
// Handle the error gracefully
console.error('Error caught:', error.message);
} finally {
// Runs no matter what
console.log('Execution completed.');
}
✅ 4. Debugging Techniques
- Console Logging: Use
console.log(),console.error()to output values and errors. - Browser Developer Tools: Use breakpoints to pause execution and inspect variables.
- Debugger Statement: Insert
debugger;in your code to trigger debugger pause. - Stack Traces: Review error stack traces in the console to locate issues.
- Linting Tools: Use ESLint or similar tools to catch errors before running code.