JavaScript Intermediate Day 7: Error Handling & Debugging

Goal of this Day

Today you will learn:

By the end, you will be able to catch errors and debug code effectively.

Step 1: try...catch

Use try...catch to safely handle errors:


try {
  JSON.parse("invalid");
} catch (error) {
  console.log("Error caught!");
}

Explanation:

Step 2: Debugging in Browser

Use browser developer tools to debug:

Step 3: Common Errors

Practice


try {
  JSON.parse("invalid");
} catch (error) {
  console.log("Error caught!");
}

Task

Write code that handles an error safely:


function safeParse(json) {
  try {
    return JSON.parse(json);
  } catch (error) {
    console.log("Invalid JSON:", error.message);
    return null;
  }
}

// Example usage
const data = safeParse('{"name": "John"}');
const badData = safeParse("invalid");