JavaScript Error Handling

Errors happen — good error handling prevents crashes and helps debug issues. JavaScript offers try...catch, finally, custom throw, and more.

1) try...catch

Wrap risky code inside try. If an error occurs, catch runs.


try {
  nonExistent();
} catch(err) {
  console.log('Error:', err.message);
}

2) finally

The finally block always runs (cleanup code).


try {
  console.log('Working...');
} catch {
  // no error
} finally {
  console.log('Always runs');
}

3) throw

You can throw your own errors with throw.


function divide(a, b) {
  if(b === 0) throw new Error('Cannot divide by zero');
  return a / b;
}

4) Error Object

Errors have name, message, and stack properties.


try {
  JSON.parse('{bad json}');
} catch(err) {
  console.log(err.name);
  console.log(err.message);
}

5) Custom Error Class

Extend Error to create your own error types.


class ValidationError extends Error {
  constructor(msg) {
    super(msg);
    this.name = 'ValidationError';
  }
}
throw new ValidationError('Invalid input');

6) Async Errors with async/await

Use try...catch inside async functions to handle rejected promises.


async function getData() {
  try {
    await Promise.reject('Oops');
  } catch(e) {
    console.error(e);
  }
}
getData();

7) Global Error Handling

Capture uncaught errors with window.onerror.


window.onerror = (msg, url, line) => {
  console.log('Global error:', msg);
};
nonExistent(); // triggers handler
Tip: Always provide meaningful error messages. Never expose sensitive info in errors shown to users.