Skip to main content

11. Error Handling

Errors are inevitable in programming. Handling them gracefully makes your code robust and user-friendly. JavaScript provides powerful tools for catching, reporting, and recovering from errors.


11.1 Error Types

  • Syntax Errors: Mistakes in code structure (caught at parse time)
  • Runtime Errors: Occur during execution (e.g., undefined variable)
  • Logical Errors: Code runs but does the wrong thing

11.2 Error Object

When an error occurs, JavaScript creates an Error object with useful info:

try {
throw new Error('Something went wrong');
} catch (e) {
console.log(e.message); // 'Something went wrong'
console.log(e.name); // 'Error'
console.log(e.stack); // stack trace
}

11.3 Handling Errors

try-catch

try {
let x = y + 1; // y is not defined
} catch (err) {
console.error('Error:', err.message);
}

try-catch-finally

The finally block always runs, even if there’s an error.

try {
// ...
} catch (e) {
// ...
} finally {
console.log('Cleanup');
}

Throwing Errors

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

Custom Errors

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

Async Error Handling

Use catch with promises or try-catch with async/await.

fetch('bad-url')
.then(res => res.json())
.catch(err => console.error(err));

async function getData() {
try {
let res = await fetch('bad-url');
} catch (e) {
console.error(e);
}
}

Next: Advanced JavaScript Utilities