JavaScript Tutorial in Hindi #37 | Error Handling & Debugging Techniques

✅ 1. What is Error Handling in JavaScript?

  1. Error handling is the process of detecting and managing errors that occur while your code runs.
  2. It helps avoid crashing the program and provides meaningful feedback to users or developers.
  3. Allows graceful recovery or alternative actions when something goes wrong.

✅ 2. Types of Errors in JavaScript

Error TypeDescriptionExample
Syntax ErrorCode that violates JavaScript grammar rulesMissing a closing bracket {
Reference ErrorAccessing a variable that doesn’t existUsing an undefined variable
Type ErrorPerforming an operation on incompatible typeCalling a number like a function
Range ErrorNumber out of allowable rangeCreating array with negative length
Custom ErrorsProgrammer-defined errors using throwthrow new Error('Invalid input')


✅ 3. The try-catch Block in JavaScript

  1. Used to catch runtime errors and handle them without stopping the script.
  2. try block contains the code that may throw an error.
  3. catch block handles the error.
  4. Optional finally block 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

  1. Console Logging: Use console.log(), console.error() to output values and errors.
  2. Browser Developer Tools: Use breakpoints to pause execution and inspect variables.
  3. Debugger Statement: Insert debugger; in your code to trigger debugger pause.
  4. Stack Traces: Review error stack traces in the console to locate issues.
  5. Linting Tools: Use ESLint or similar tools to catch errors before running code.