try
Wraps code that may throw.
try, catch and throw let you protect risky code, handle expected failures and create your own errors.
function requireTitle(record) {
if (!record.title) {
throw new Error("Title is required");
}
}
Errors & Debugging
Code inside try runs normally until something throws. When an error is thrown, JavaScript jumps to catch.
throw should be used when a function cannot honestly return a useful result. It communicates that normal execution must stop.
A catch block should either handle the problem, convert it into a useful result or rethrow it. Catching everything and doing nothing is worse than crashing loudly.
Wraps code that may throw.
Receives the thrown error.
Creates an error path.
Runs after try/catch whether success or failure happened.
Examples
function createRecord(input) {
if (typeof input.title !== "string") {
throw new TypeError("title must be a string");
}
return { title: input.title.trim() };
}
function createRecord(input) {
if (!input.title) {
return false;
}
}
// The caller has to guess what false means.
Code patterns
These examples focus on the debugging patterns you will reuse: safe parsing, throwing, custom error types, console inspection, breakpoints and async failure handling.
Stop when required input is missing.
function requireTitle(record) {
if (!record.title) {
throw new Error("Title is required");
}
}
Handle risky parsing.
try {
const data = JSON.parse(raw);
} catch (error) {
console.error(error.message);
}
Add context without hiding the cause.
try {
parseConfig(raw);
} catch (error) {
throw new Error("Could not parse config", { cause: error });
}
Clean up regardless of outcome.
let busy = true;
try { runTask(); }
finally { busy = false; }
Rules that matter
Debugging starts before something breaks. Clear error types, helpful messages and visible failure states make the code easier to repair.
throw new Error gives stack and message.
Catch where you can recover or add context.
Low-level code may not know how to recover.
It runs after success and failure.
Do not hide failures you cannot handle.
A catch block should not become unrelated logic.
Production thinking
try/catch/throw gives JavaScript a clear failure path instead of returning confusing values from every function.
Caught errors should become understandable UI messages when users can take action.
Production boundaries should catch expected errors and report unexpected ones.
Rendering code should fail visibly during development rather than silently output incomplete content.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
A JavaScript feature is not production-ready until you know how it fails and how you will inspect that failure.