Labs ICT
โญ Pro Login

Try & Catch

1 min read | JavaScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

try...catch

The try block contains code that might throw. If an error occurs, execution jumps to the catch block.

try {
  let result = 10 / 0;
  console.log(result);
  throw new Error("Manual error");
} catch (error) {
  console.log("Caught:", error.message);
}

finally

The finally block runs regardless of whether an error was thrown or caught. It's perfect for cleanup.

function divide(a, b) {
  try {
    if (b === 0) throw new Error("Division by zero");
    return a / b;
  } catch (err) {
    console.log(err.message);
    return null;
  } finally {
    console.log("Cleanup complete");
  }
}

console.log(divide(10, 2));
console.log(divide(10, 0));

throw

You can throw anything: strings, numbers, booleans, or Error objects. Throwing an Error object is best practice.

function validateAge(age) {
  if (age < 0) throw new Error("Age cannot be negative");
  if (age < 18) throw new Error("Must be 18 or older");
  return "Valid age";
}

try {
  console.log(validateAge(15));
} catch (err) {
  console.log("Validation error:", err.message);
}

๐Ÿงช Quick Quiz

What keyword catches errors in a try block?