Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - 1. What is an Error?
  • - 2. try...catch Statement
  • - 3. The finally Block
  • - 4. Throwing Custom Errors
  • - 5. Common Error Types
  • - Mini Challenge

16. Error Handling in JavaScript

Level: IntermediateDuration: 15m

Errors happen — even in the cleanest code. JavaScript gives us tools to handle them gracefully so your program doesn’t crash unexpectedly and users get helpful feedback instead.

1. What is an Error?

An error is something that stops the normal flow of your program. For example, trying to access a variable that doesn’t exist or dividing by zero (in math-related logic) might cause an error.

javascript
console.log('Before error');

nonExistentFunction(); // ❌ ReferenceError

console.log('After error'); // This line will never run

Once an error occurs, the rest of the code in that function won’t execute unless we catch it.

2. try...catch Statement

The `try...catch` statement lets you run risky code inside a `try` block. If an error happens, it’s 'caught' in the `catch` block, so your app can recover or show a friendly message.

javascript
try {
  console.log('Before error');
  nonExistentFunction();
  console.log('This will not run');
} catch (error) {
  console.error('⚠️ Oops, something went wrong:', error.message);
}

console.log('After handling error');

The program continues even after an error occurs — it doesn’t crash the whole script.

3. The finally Block

`finally` runs after `try` and `catch`, no matter what. It’s perfect for cleanup tasks, like closing a file or hiding a loading spinner.

javascript
try {
  console.log('Trying to fetch data...');
  throw new Error('Network connection lost');
} catch (error) {
  console.error('Caught an error:', error.message);
} finally {
  console.log('✅ Cleaning up...');
}

4. Throwing Custom Errors

You can create your own errors with `throw`. This helps you signal specific problems in your app, like invalid user input or missing data.

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

try {
  console.log(divide(10, 0));
} catch (error) {
  console.error('Custom error:', error.message);
}

5. Common Error Types

  • ReferenceError — accessing a variable that doesn’t exist
  • TypeError — using a value in the wrong way (e.g., calling something that’s not a function)
  • SyntaxError — code that breaks JavaScript rules (usually caught before running)
  • RangeError — a number that’s out of range (like `new Array(-1)`)

Mini Challenge

Write a function parseUserData(jsonString) that takes a JSON string and returns the parsed object. If parsing fails, catch the error and log a friendly message like 'Invalid JSON data'. Always print 'Parsing complete' using 'finally', whether it succeeded or not.

javascript
// Example:
parseUserData('{"name": "Chrise"}'); // ✅ Works
parseUserData('not-valid-json'); // ⚠️ Shows error message

This will test your understanding of 'try...catch...finally' and how to handle runtime errors safely.