Labs ICT
โญ Pro Login

Try & Catch

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);
}
Try it Yourself โ†’

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));
Try it Yourself โ†’

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);
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword catches errors in a try block?