Skip to content
Justice Tech School

Errors and try...catch

When code throws an error the program stops, unless you catch it. Put risky code in try, handle the problem in catch and use finally for clean up that must always happen. You can throw your own errors with throw new Error("message").

Example
function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
try {
  console.log(divide(10, 2));
  console.log(divide(1, 0));
} catch (error) {
  console.log("Caught: " + error.message);
} finally {
  console.log("Done");
}

Exercise

Which block runs when an error is thrown?

try {
  risky();
}  (e) {
  console.log(e);
}

Quiz Test

When does the finally block run?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.