JavaScript try...catch

Beginner
6 min read
Updated: Nov 2026
3 examples

Definition and Usage

try...catch runs a block of code and, if something throws, jumps to catch so you can handle the error instead of crashing.

JavaScript Syntax

JavaScript
try {
  JSON.parse("{bad");
  console.log("ok");
} catch (err) {
  console.log("Caught: " + err.name);
}
Try it Editor

How It Works

  1. try runs. Parsing invalid JSON throws.
  2. catch handles. Control jumps to catch; "ok" never prints.
  3. Keep going. The program continues after the catch block.

Examples

Example 1 — finally Cleanup

finally runs whether or not an error occurred.

JavaScript
let status = "start";
try {
  throw new Error("fail");
} catch (err) {
  status = "caught";
} finally {
  status += "+done";
}
console.log(status);
Try it Editor

How It Works

  1. throw jumps. Execution enters catch.
  2. finally always. Cleanup runs after catch.

Example 2 — Safe JSON Parse

Return a fallback object when parsing fails.

JavaScript
function safeParse(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    return {};
  }
}
console.log(JSON.stringify(safeParse("{\"a\":1}")));
console.log(JSON.stringify(safeParse("nope")));
Try it Editor

How It Works

  1. Valid JSON. Returns the parsed object.
  2. Invalid JSON. Catch returns {}.

Example 3 — Rethrow Unknown Errors

Handle expected errors and rethrow the rest.

JavaScript
function readNumber(text) {
  try {
    const n = Number(text);
    if (Number.isNaN(n)) throw new TypeError("not a number");
    return n;
  } catch (err) {
    if (err instanceof TypeError) return 0;
    throw err;
  }
}
console.log(readNumber("x"));
Try it Editor

How It Works

  1. Expected TypeError. Converted to a safe 0.
  2. Others propagate. Unexpected errors can still bubble up.

Frequently Asked Questions

A control structure that catches thrown errors so you can recover or report them.

After try completes or after catch handles an error—always, even if you return inside try/catch.

Catch errors you can handle. Avoid empty catch blocks that hide bugs.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful