Back to Explore
GuideVibeFix editorialUpdated Nov 19, 2026

Stop guessing at errors: try...catch and Error, explained plainly

A page that crashes on a bad JSON string, a null no one checked, an error thrown inside a callback that no try could catch. This guide follows MDN's try...catch, Error, and throw references: three kinds of errors, the three try shapes, finally's rules, nested tries and re-throwing, branching with instanceof, the Error family, cause, and the callback trap.

Real photo: a young programmer debugging code at two monitors, the right screen full of red error text

First, the boundaries. The site already has “When exactly does your code run? The JavaScript event loop”, about when code executes; “Stop letting async code fail quietly: Promise and async/await”, about how to write asynchronous code; and “The day your users saw a white screen and you were the last to know: error monitoring and crash reporting”, about spotting errors after launch. This guide covers none of those. It covers one thing: when a piece of synchronous code goes wrong halfway through, how do you catch the error, identify it, and decide whether to handle it or let it go. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. This time it is about how its order page handles errors: menu data that comes back broken, a customer record missing a piece, an order submission that dies halfway. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about error syntax and behavior comes from three MDN reference pages — “try...catch”, “Error”, and “throw”. The sources are listed in this article's meta information and evidence record. The examples in the docs — opening a file and closing it again, sorting an order, a read-file callback — are the docs' own examples, not real services. By the end of this guide you should be able to do three things: look at an error and tell which kind it is, catch the ones worth catching, and let go of the ones that should not be caught; write the branching and re-throwing inside catch instead of catching everything in one net; and when an error pops out of a callback, know why the try outside cannot catch it and what to write instead.

Step 1: Sort errors into three kinds first — try can only catch one of them

The most common beginner mistake is assuming try...catch can catch every error. Errors actually come in three kinds, and try can only catch the middle one. The first kind is a syntax error: the file itself is written wrong — a missing bracket, a misspelled keyword — and the code fails at the parsing stage before it even starts running. Wrapping it in try does nothing, because the try itself sits inside the same broken file. The second kind is a runtime error: the code is written fine, but it blows up when it reaches a certain line — reading a variable that does not exist, calling a function that does not exist, passing bad data to JSON.parse. try can catch this kind. The third kind is a logic error: the code runs through to the end, reports nothing, but the result is wrong — an order total that comes out negative, a menu missing a dish. try cannot catch this kind; only tests, checks, and printing the key numbers will find it. The Greenstone Cafe order page has hit all three: once, a script file was missing a brace and the page went blank, and no try could help; most of the time the errors were runtime errors that try caught; the hardest ones to find were logic errors, where the total was wrong but the page looked perfectly fine. Remember the first sentence: ask “which kind of error is this” before deciding whether try is any use.

Step 2: try comes in three shapes, and catch or finally must be there

A try statement always starts with a try block, followed by a catch block or a finally block, or both — giving three forms: try...catch, try...finally, and try...catch...finally. MDN adds a warning: unlike if or for, the try, catch, and finally blocks must be blocks — code wrapped in braces — not single statements. Writing try doSomething() on one line is itself a SyntaxError. The try block holds the statements to execute; the catch block holds what to do if an exception is thrown in the try block; the finally block holds what must run before control flow leaves the construct, whether an exception was thrown or caught. The cafe order page uses try...catch...finally on “submit order”: the try sends the request, the catch tells the customer “submission failed, please try again”, and the finally turns the “submitting” button back to clickable. Remember the rule: try cannot stand alone — keep at least one of catch and finally.

Step 3: On error, jump to catch at once; with no error, catch is never even looked at

The control flow rule is simple. If any statement inside the try block throws, or a function called from inside the try block throws, control shifts to the catch block immediately, and the rest of the try block is skipped. If the try block runs through without throwing, the catch block is skipped entirely — it is never even looked at. The finally block, by contrast, always runs before control flow exits the construct: after the try block finishes, after the catch block finishes, and even when an exception was thrown and nobody caught it. MDN's file example is exactly this pattern: open the file first, write to it inside try, and close it in finally — whatever happens while writing, the file is always closed. The cafe order page writes “open the order drawer” the same way: try computes the total and renders the order, catch shows “could not compute it”, and finally switches off the loading spinner. Remember the rule: catch runs only on error, finally always runs.

Step 4: What the e in catch is, and how long it lives

The e in parentheses after catch is the value that was thrown, which MDN calls the exceptionVar. Three things on it matter most: name, the type name of the error, such as TypeError or SyntaxError; message, a human-readable sentence, such as “oops” or “Parameter is not a number!”; and stack, the call stack at the moment of the error, whose format varies a little between browsers. e only lives inside the catch block's scope — step outside catch and it is gone. It does not have to be a single identifier: MDN says you can use a destructuring pattern to take several at once, as in catch ({ name, message }), pulling the name and the message straight out. But be careful: a name pulled out by destructuring cannot collide with a variable declared inside the catch block, or you get a SyntaxError. There is also a shorter form: if the catch block never uses the error at all, you can drop e together with its parentheses and write catch { on its own. MDN's isValidJSON example does exactly this: JSON.parse(text) inside try, return true if it works, return false if it fails — the error itself is never even looked at. Remember the rule: to identify an error, read e's name and message; if you do not need to identify it, even the parentheses can go.

Step 5: What gets thrown is not always an Error — normalize it when you catch it

throw can be followed by any expression: throwing a string, a number, or an object is all legal. MDN's advice is that in practice, the exception you throw should always be an Error object or an instance of an Error subclass, such as RangeError, because the code that catches the error may expect certain properties, such as message, to be present on the caught value. Throw a bare string and the catcher reads e.message only to get undefined. The safer habit is to normalize inside catch first: if (!(e instanceof Error)) { e = new Error(e); }, wrapping anything that is not an Error into one before going on. The cafe order page learned this the hard way: an early version threw the string “menu could not be read”, and the catch block wrote console.error(e.message) — which printed only undefined, hiding the real reason. After switching to throwing new Error("menu could not be read") everywhere, the catch block's message showed the reason plainly in the log. Remember the rule: only throw Errors, and wrap anything that is not an Error into one when you catch it.

Step 6: Never write return or throw inside finally — they overwrite what came before

finally has one rule that is easy to trip over. A return, throw, break, or continue written in the try or catch block is deferred until after the finally block has finished running; the return value expression itself is evaluated before entering finally. MDN's safeWriteMyFile example works this way: the try returns writeMyFile(theData), the value to return is computed first, then finally closes the file, and only then does the function actually return. But if the finally block itself contains another control flow statement, that statement overrides the earlier one, with no negotiation. MDN's doIt example makes it plain: the try pushes “try” into an array, sorts it, and prepares to return the sorted array; the finally pushes “finally” and returns the array too, and the result is the three-element array “try”, “z”, “finally” — not the two elements the try had prepared. The sharper example is: the try throws “try”, the catch throws “catch”, and the finally returns “finally” — and the function ends up returning “finally”, with no error thrown at all. MDN's conclusion is blunt: it is generally a bad idea to use control flow statements in the finally block because they can override the effect of previously executed control flow statements, which is rarely intended. Remember the rule: finally holds cleanup code only — no return, no throw.

Step 7: try can nest, and an error is caught only once, by the nearest catch

try statements can nest inside one another. If an inner try has no catch block, only a finally, an error thrown inside it is caught by the enclosing try's catch block instead. MDN's nesting example spells out the order: the inner try throws new Error("oops"), the inner finally runs and logs “finally”, then the outer catch takes it and logs “outer” plus “oops”. If the inner try has its own catch, the inner one takes it first and logs “inner” plus “oops”, then finally runs, and the outer catch never sees it — unless the inner catch throws the error again. Any given exception will be caught only once by the nearest enclosing catch block unless it is rethrown. Re-throwing means writing throw e inside catch, sending the unchanged error upward so the outer layer can decide what to do. The cafe order page splits “restore a saved order from local storage” this way: the inner catch handles only the one case of “saved data is broken”, and if it cannot fix it, it re-throws; the outer catch then tells the customer “order could not be restored”, in one place. Remember the rule: handle it in the inner layer if you can, re-throw if you cannot, and never swallow an error quietly in the inner layer.

Step 8: There is no per-type catch syntax — branch with instanceof yourself

Java lets you write catch (RangeError e), catching by type. JavaScript does not. MDN says that to make “conditional catch blocks” you combine try...catch with if...else if...else yourself: if e instanceof TypeError, do this; else if e instanceof RangeError, do that; and in the final else, re-throw the errors you did not recognize. The common use is to catch — and silence — only a small subset of expected errors, and re-throw the error in other cases. MDN's example catches only RangeError in place and throws everything else back with throw e. The Error page shows the same pattern: test EvalError, then RangeError, one by one, and in the last else throw e so the error keeps travelling upward unhandled. The cafe order page writes “parse the note the customer typed” this way: a SyntaxError from JSON.parse is handled in place as “the note format is wrong, please type it again”, and every other error is re-thrown. Remember the rule: JavaScript has no catch by type — branch with instanceof, and re-throw what you do not recognize.

Step 9: throw is your tool for raising an error yourself — only an Error counts

The throw statement is a single line: throw followed by an expression. Running it generates an exception that penetrates through the call stack until some catch takes it. MDN's getRectArea example shows the most common use: if a parameter is not a number, throw new Error("Parameter is not a number!"), and the try...catch outside takes it and prints “Error: Parameter is not a number!”. MDN's sum example shows throwing by type: if a non-number slips into the arguments, throw new TypeError("Can only add numbers"), because the type of the error is itself information — the catcher sees TypeError and knows immediately that a type was wrong. There is also a syntax trap: the syntax forbids line terminators between the throw keyword and the expression to be thrown. Break the line there and automatic semicolon insertion turns it into throw; followed by a separate new Error() — invalid code, because unlike return, throw must be followed by an expression. MDN's workaround is to wrap the expression in parentheses before breaking the line. Remember the rule: raise errors with throw, throw only Errors, and never break the line after throw.

Step 10: The Error family each minds its own business — the name tells you where it went wrong

Besides the generic Error, JavaScript has a whole family, each minding its own business. TypeError means a variable or parameter is not of a valid type — adding a string as if it were a number, or reading a property off null. ReferenceError means de-referencing an invalid reference, such as using a variable name that was never declared. RangeError means a numeric variable or parameter is outside its valid range. SyntaxError means a syntax error — and JSON.parse throws exactly this when it receives a broken string. URIError means encodeURI or decodeURI was passed invalid parameters. EvalError concerns the global function eval. AggregateError wraps several errors in a single error when multiple errors need to be reported by an operation, for example by Promise.any(). InternalError is an engine-internal error, such as “too much recursion”. MDN's opening try...catch example is the best starting point: the try calls a function that does not exist, nonExistentFunction, and what comes out is a ReferenceError — the name itself says “the reference was wrong”. The three kinds the cafe order page meets most often line up neatly: broken data into JSON.parse is a SyntaxError, reading the address of a customer who never logged in is a TypeError, and a misspelled variable name is a ReferenceError. Remember the rule: read the name first, then the message — the name is the error's category.

Step 11: Leave a cause on the error, so the chain of evidence survives

Sometimes one place can fail for several reasons, and the failures look almost the same, so you cannot tell whose fault it was. MDN's answer is to catch the low-level error and throw a new, more specific one, passing the original error into the new Error as its cause: throw new Error("Failed in some way", { cause: err }). That way the upper layer catches the new error and can still follow err.cause back to the original error and its original stack trace. MDN adds a note for library authors: prefer to use error cause to discriminate between different errors emitted, rather than asking your consumers to parse the error message — because the moment the wording changes, every consumer's parsing code breaks. Custom error types work the same way: class MyError extends Error, and its constructor passes options through to super(message, options), which is what installs the cause property. The cafe order page does this on “submit order”: the low-level failure might be a dropped network or broken menu data, and the catch wraps either into new Error("order submission failed", { cause: err }) before throwing upward. The upper layer reads the message alone to know which step failed, and follows cause downward when it needs to dig deeper. Remember the rule: do not tell errors apart by parsing message text — leave an evidence chain with cause.

Step 12: An error thrown inside a callback cannot be caught by the try outside

This is the point that confuses beginners most: try...catch can only catch errors in the same synchronous run. MDN's throw page tells a callback story: readFile("foo.txt", (err, data) => { if (err) { throw err; } }). By the time that callback runs, the try outside has long since finished, so nobody catches the thrown error and the program crashes — unless the readFile function itself catches the error, or the program runs in a context that catches top-level errors. MDN's proper fix is to wrap the callback in a Promise: inside readFilePromise, an err calls reject(err), and outside, await waits for it and try...catch takes it. The async writing details are covered in full in the site's “Stop letting async code fail quietly: Promise and async/await” guide; the boundary to remember here is simple: synchronous code uses try...catch, asynchronous code first becomes a Promise and then uses try...catch — never write a throw inside a callback and expect the try outside to catch it. The cafe order page once lost an error exactly this way: a throw inside a timer callback crashed the page on schedule, and the try wrapped around the outside was no use at all. Remember the rule: a throw inside a callback cannot be caught by try — wrap it into a Promise first.

Step 13: Do not catch carelessly — an empty catch hides the bug

The last rule is judgment, not syntax. catch means “I know this error can happen, and I know what to do when it does” — a bad JSON.parse gets a “please type it again” prompt, broken local data gets cleared and rebuilt. An empty catch block, or a catch that takes every error and does nothing with it, is the worst way to write it: the error really does stop being reported, but the feature quietly breaks too — the customer clicks to order and nothing happens, the order is never saved, and there is nothing in the log to explain why. MDN's conditional catch example is the positive version of the same rule: catch only the small set of expected errors in place, and re-throw the rest so they blow up, get seen, and get fixed. The cafe order page has a hard rule: a catch block must do at least one of three things — give the customer a message they can understand, write the error down, or re-throw it. A catch that does nothing gets sent back in review. Remember the rule: if you do not know how to handle it, do not catch it; catching an error and doing nothing hides it.

Bar chart of 90 errors in one month, by cause

Checklist: run through this list when your try...catch is written

The chart below shows the causes of 90 errors in one month on the fictional Greenstone Cafe order page: JSON.parse received bad data, a SyntaxError, 26 times (28.9%); reading a property off null or undefined, a TypeError, 22 times (24.4%); a misspelled variable name, a ReferenceError, 14 times (15.6%); an empty catch swallowed the error and left no clue, 12 times (13.3%); an error thrown inside a callback with nobody to catch it, 9 times (10.0%); a return written inside finally, overwriting the earlier result, 7 times (7.8%). 26 + 22 + 14 + 12 + 9 + 7 = 90, and the percentages add up to 100.0%. The numbers are invented examples; the lessons are real, and the top three are all about “errors misidentified or uncaught”, not “errors too hard to fix”. When your own try...catch is written, run through this list: is this a syntax error, a runtime error, or a logic error, and is try any use here; did the try get a catch or a finally, and is neither missing; are you reading name or message in the catch, and did you normalize values that are not Errors; does finally hold only cleanup, with no return and no throw; did nested tries re-throw the errors they cannot handle; does the branching use instanceof, and are unrecognized errors re-thrown; are the errors you throw yourself Errors, with no line break after throw; did you leave a cause, and do custom errors pass options to super; did throws inside callbacks get wrapped into Promises first; and does every catch do at least one thing — prompt, log, or re-throw. When all ten pass, the error handling is done.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering
Real photo: a Casio scientific calculator on a wooden desk showing 123456789 + 987654321 = 1111111110, beside handwritten math notebooks, a pen, a mug, and a laptop edge
Guide
Don't let 0.1 + 0.2 break your bill: JavaScript numbers and Math, explained plainly

Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.

Tool TipsFrontend EngineeringAI Coding