Put the operation that may fail inside try, handle the problem in catch, and release temporary resources in finally. This gives an exception in JavaScript a clear route from its source to a place where the program can respond. If you are trying JavaScript error handling for the first time, a small request makes that route easy to follow.
Try JavaScript Error Handling With a Small Request
Imagine a page that loads a profile while a spinner is visible. The following browser example requests a JSON document, checks the response, and always hides the spinner. The URL is illustrative; substitute an endpoint that returns a profile with a name property.
async function showProfile(url, spinner) {
spinner.hidden = false;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Profile request failed: ${response.status}`);
}
const profile = await response.json();
console.log(`Hello, ${profile.name}`);
} catch (error) {
console.error("Could not show profile:", error);
} finally {
spinner.hidden = true;
}
}
When you try JavaScript examples like this, follow one statement at a time. The spinner appears before the request starts. If the request succeeds and the body contains valid JSON, the greeting is logged. If a step fails, control moves to the handler; cleanup follows either path. The caller must pass an existing DOM element as spinner.
This example brings several javascript exceptions into one flow: a network failure, an explicit error for an unsuccessful HTTP response, and a JSON parsing failure. Each reaches the same handler, but its message helps identify the failing step. These javascript exceptions illustrate separate points of failure. In a real interface you might also display a short failure message near the profile.
What throw changes
A JavaScript exception can start with an explicit throw. The throw statement stops the normal sequence at that point and passes a value outward. Here, fetch can fulfill with a response even when the server sends a status such as 404 or 500, so response.ok is checked explicitly. A failed check creates an Error and throws it before the body is read.
JavaScript exceptions travel up the call stack until an enclosing handler catches them. If a helper called within try throws an exception in JavaScript, its remaining statements are skipped too. The nearest matching catch receives the JavaScript exception value; if no suitable handler handles it, the failure reaches the surrounding environment. In an async function, an uncaught failure rejects the function’s returned promise.
You can try handling JavaScript errors with a deliberately missing profile URL to see the status in the console. Then use a valid endpoint and compare the path through the same function. Trying this JavaScript example along both paths makes the skipped work visible: after the explicit throw, neither JSON parsing nor the greeting runs.
Read the error before deciding what to do
An Error object carries a message and a name, and environments commonly provide a stack showing where the error originated. Here the message includes the HTTP status. JavaScript exception objects can also have a cause when one error wraps another, preserving context for diagnosis. Specific types such as TypeError help describe certain failures. The type of a JavaScript exception can guide the response.
When you try handling JavaScript errors with your own inputs, throw an Error rather than a bare string: a structured object gives the handler and debugging tools more context. JavaScript permits any value to be thrown, however, so code receiving unknown values should not assume every caught value has a message property.
When trying error handling in JavaScript, choose a handler that can act at a level that understands the failure. This example can hide the spinner and report that the profile was unavailable. A lower-level parser might instead add context and rethrow, leaving the screen component to decide what to show. If you cannot recover there, throw error passes the same value to an outer handler. Silently catching every problem can leave a page looking successful when its data never arrived.
Clean up on both paths
The finally block runs after try completes or after catch handles a failure, including when a return or throw is pending. In this example it hides the spinner whether the profile loads or fails. Similar cleanup might release a lock, remove a temporary listener, or close a resource that was actually acquired.
For an exception in JavaScript, cleanup belongs close to the operation that owns the resource. When trying cleanup in JavaScript, track whether acquisition succeeded before attempting release. Avoid returning or throwing from finally unless you intend to replace the earlier result or error: a new control flow there can hide the original failure. If cleanup itself throws, that new error also needs attention.
Put asynchronous failures inside the boundary
A JavaScript exception handler in synchronous code sees a throw that occurs while its try block is executing. A promise can reject later, after that block has finished. A JavaScript exception raised in a later callback needs its own handling boundary. Calling a promise-returning function inside try without awaiting it therefore does not make the surrounding catch handle its later rejection.
With await inside an async function, a rejected promise throws its rejection reason at the await point. That is why the handler in showProfile can catch both a failed fetch and a failed response.json(). To try JavaScript with a promise chain instead, attach a rejection handler to the returned promise:
showProfile(url, spinner).catch((error) => {
console.error("Unexpected failure:", error);
});
The inner handler normally consumes request errors, so this outer handler catches failures that escape, such as a throw from cleanup. A .catch() callback returns a new promise: returning a value recovers the chain, while throwing rejects the new promise. Return or await that chain if another caller needs to know when it finishes. JavaScript exceptions in a separately scheduled callback require a handler in that callback or a promise that rejects for that failure.
Recognize the common missed rejection
The most likely surprise is a promise that rejects after its surrounding try has already ended. You may see an unhandled rejection in the console while the expected handler never runs. If you try handling JavaScript errors and see that pattern, find the promise-producing call, then await it inside the intended try or attach .catch() to its chain. Check that the cleanup still runs after the asynchronous operation settles; otherwise a spinner can disappear while the request is still in flight.
