JavaScript Fundamentals

Error Handling & Debugging

Understanding Error Handling & Debugging

Error handling is crucial for writing robust JavaScript applications. Learning how to properly catch and handle errors, along with effective debugging techniques, will help you create more reliable code and solve problems more efficiently.

Try-Catch Statements

// Basic Try-Catch
try {
  // Code that might throw an error
  const result = someUndefinedVariable + 1;
} catch (error) {
  console.error('An error occurred:', error.message);
}

// Try-Catch-Finally
try {
  // Attempt to parse JSON
  const data = JSON.parse('{"invalid": json}');
} catch (error) {
  console.error('Parsing failed:', error);
} finally {
  console.log('This runs regardless of success or failure');
}

Error Types

// Common Error Types
// ReferenceError
try {
  console.log(undefinedVariable);
} catch (error) {
  console.log(error instanceof ReferenceError); // true
}

// TypeError
try {
  null.toString();
} catch (error) {
  console.log(error instanceof TypeError); // true
}

// SyntaxError
try {
  eval('if (true) {');
} catch (error) {
  console.log(error instanceof SyntaxError); // true
}

Custom Errors

// Custom Error Class
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
  }
}

// Using Custom Error
function validateUser(user) {
  if (!user.name) {
    throw new ValidationError('Name is required');
  }
  if (!user.email) {
    throw new ValidationError('Email is required');
  }
}

try {
  validateUser({ name: '', email: '' });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation failed:', error.message);
  } else {
    console.log('Unknown error:', error);
  }
}

Debugging Techniques

// Debugging Techniques
// Console Methods
console.log('Basic logging');
console.info('Information');
console.warn('Warning message');
console.error('Error message');
console.table([{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]);

// Debugger Statement
function complexCalculation(x, y) {
  debugger; // Code execution will pause here in dev tools
  const result = x * y / (x - y);
  return result;
}

// Performance Measurement
console.time('loop');
for (let i = 0; i < 1000000; i++) {
  // Some operation
}
console.timeEnd('loop');