Back
LearnJavaScript From ZeroHandling errors with try / catch

Handling errors with try / catch

1 min read

Things will go wrong — plan for it

Real programs hit problems: bad input, a failed network call, missing data. If you do nothing, one error can crash the whole script. JavaScript gives you a safety net: try / catch.

try {
  let data = JSON.parse("not valid json");
  console.log(data);
} catch (error) {
  console.log("Something went wrong: " + error.message);
}

Read it as: "try to run this. If it throws an error, jump to catch instead of crashing." The program keeps running.

Why is this so important?

Because you cannot control everything — a user types garbage, the internet drops, a file is missing. try/catch lets you handle the failure gracefully and show a friendly message instead of a broken page.

Throwing your own errors

You can also raise an error on purpose when something is not allowed:

function withdraw(amount) {
  if (amount <= 0) {
    throw new Error("Amount must be positive");
  }
  return amount;
}

That throw jumps straight to the nearest catch.

finally — runs no matter what

try {
  // risky work
} catch (e) {
  // handle the error
} finally {
  console.log("This always runs");
}

Use finally for cleanup that must happen either way.

try = attempt risky code, catch = handle the failure, finally = always run. This is how real apps stay alive instead of crashing.

Tip