try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.

The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.

It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

if (isNaN(numberVariable))
{
    alert('you should enter a valid number');
}
Answer from Saeed Neamati on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › try...catch
try...catch - JavaScript | MDN
The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control ...
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › error handling
Error handling, "try...catch"
If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err). The err variable (we can use any name for it) will contain an error object with details about what happened. So, an error inside the try {...} block does not kill the script – we have a chance to handle it in catch.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Control_flow_and_error_handling
Control flow and error handling - JavaScript | MDN
... The catch block specifies an identifier (exception in the preceding syntax) that holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown. JavaScript creates this identifier when the catch block is entered.
🌐
W3Schools
w3schools.com › js › js_errors.asp
JavaScript Error Statements
In JavaScript, the try statement ... it works with finally. And sometimes it works with throw. The try block contains the code that might throw an error....
🌐
freeCodeCamp
freecodecamp.org › news › try-catch-in-javascript
Try/Catch in JavaScript – How to Handle Errors in JS
December 30, 2020 - This is basically how a try/catch is constructed. You put your code in the try block, and immediately if there is an error, JavaScript gives the catch statement control and it just does whatever you say.
🌐
W3Schools
w3schools.com › jsref › jsref_try_catch.asp
JavaScript try/catch/finally Statement
The try...catch...finally statements combo handles errors without stopping JavaScript. The try statement defines the code block to run (to try).
Top answer
1 of 7
51

try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.

The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.

It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:

if (isNaN(numberVariable))
{
    alert('you should enter a valid number');
}
2 of 7
44

I found this from a post here:

When Should You Use try-catch?

The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch statement, the browser’s usual error handling mechanism will be disabled.

You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.

Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.

The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.

When Should try-catch be Avoided?

You shouldn’t use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.

🌐
Reddit
reddit.com › r/learnjavascript › how often do you use try/catch blocks in your js code?
r/learnjavascript on Reddit: How often do you use Try/Catch blocks in your JS code?
February 12, 2023 -

Hello,

I am taking a udemy course on JavaScript. In the Catching and Throwing Errors lesson, the teacher introduces us to Try/Catch block. My first remark was, why would someone write an alternative if his code didn't work while he supposed to find the source of the problem. When I searched in Stackoverflow and Quora, they almost agreed on the rule of 'use as less as possible'. And because of that, I'm wondering, How often do you use in real world projects?

Thank you so much!

Top answer
1 of 6
9
There's two kinds of errors that you need to be aware of - there's programmer error, and then there's expected failures to perform operations. An example of a programmer error would be something like "I had code that did coord.x, but it turns out that coord was undefined when it shouldn't have been, so this threw an error". This is a programmer error. There's a bug in the code that needs to be fixed. Programmer errors should rarely be caught with a try-catch, but there are valid cases where you might wish to do so, including: logging adding additional information/context to the error to help with debugging it (e.g. "this error happened while we were trying to perform X operation") "error boundaries", i.e. perhaps a component on your webpage fails to load due to a programmer error - when this happens, you want to display the error in the console (to allow for additional debugging), and make the component display some user-friendly error message. This component becomes a boundary, containing the error in such a way that only the component fails to function, the rest of the webpage can still be used just fine. One important principle that I've seen violated far too often, is to make sure that the original error and stack trace that caused the error to be thrown in the first place stays preserved, and shows up somewhere. Sometimes, developers will "helpfully" throw a different error in it's place when anything goes wrong, but this makes it impossible to debug what really happened. The other type of error is "expected failures". These are things like a failure to fetch a resource over the network because, say, there's no internet, or, a failure to read a file from the disk because it doesn't exist, etc. These are all issues that you can anticipate and develop for. It's fairly common to use a try-catch for these kinds of errors. When you perform a network request, you should expect that it might fail, and you should use a try-catch to catch and handle that failure appropriately. When the network request fails, this isn't due to a bug in your code, rather, it's simply because of other conditions outside of your control. So, for example, if you want to write a function that 1. reads a JSON config file, 2. adds a new field to it, and 3. saves the updated config file, and you want this function to work, even if the file doesn't exist yet (a non-existant file should be treated as an empty JSON object), you can do that, but you'll need a try-catch around your "read-that-file" operation to catch the potential "file-not-found" error, and to handle that error appropriately. This is an expected and normal error, and it completely makes sense to try and catch this error. As an aside, file-not-found can also be a programmer error, depending on context. If that file is part of your code repository, and it's supposed to always be present, and for whatever reason, it's not, then that's a bug, not an "expected failure".
2 of 6
4
I usually use a try/catch block whenever I do something that I know probably will break in different circumstances. For example, localStorage: not every device has good support for it, so calling localStorage.getItem might fail in some older devices with cannot read property getItem of undefined because localStorage may be undefined. The result? I gracefully degrade like this: let value = ""; // try to get stored value from localStorage try { value = localStorage.getItem("stored value"); } catch { // do nothing; fail silently because the user will just assume it’s empty } Now, in almost every browser around, this’ll be fine. But on someone’s old Galaxy phone from 10 years ago, it might not. The good news is the app won’t crash: it’ll try to read from localStorage, but if it can’t, the show still goes on.
Find elsewhere
🌐
Programiz
programiz.com › javascript › try-catch-finally
JavaScript try...catch...finally Statement
The catch block handles the errors as per the catch statements. If no error occurs, the code inside the try block is executed and the catch block is skipped.
Top answer
1 of 3
13

You should only catch when you can actually do something to resolve the error.

So, you normally always catch, or otherwise handle exceptions at the top level, because you want to log or display the error somehow even if you can't resolve it.

Don't just put catch { throw } in all your functions, let the exception bubble up.

I would put a catch in functions for something like...

try 
{
   //load data over dodgy IR connection
}
catch(TransmissionException)
{
   //retry because we expect exceptions and know they are temporal
}

Or this

try
{
   //something complicated
}
catch
{
   throw //don't know what to do with errors but need a catch syntactically
}
finally
{
    //need to do some clean up
}

But not:

SavetoDisc()
{
    try
    {
       //write to disc
    }
    catch(RunOutOfDiscSpace e)
    {
        //log an error (to disc?)
        throw //only using catch block to log
    }
}

Main()
try
{
    SaveToDisc()
}
catch
{
   //log the error!
   throw (again?)
}
2 of 3
1

One() and Two() catch blocks would essentially just terminate the function and log a message that something went wrong.

This is almost never what you want to do. Normally, when you call a function you either are expecting a result or you are expecting some sort of side-effect (or both.) When you just log and exit it creates issues in both scenarios.

If your function returns a value, you need to return something to the caller. There's an alternative to exceptions using a return value that may represent an error but I'm going to ignore that option in this answer. So generally, you'll end up returning null or some other non-answer. Now you need to accommodate the possibility of this in every call to a function that might terminate abnormally. This tends to be a mess and often becomes a source of defects.

If there's some expectation of some side-effect, it's usually the case that later steps in your application depend on that being completed. If you just exit the function when something goes wrong, your caller will not have any indication that it didn't happen. In practice this means something else fails later, or worse, something happens later that puts your things into an invalid state.

The concept of an exception is that it's an alternative path to execution flow. As an analogy, let's say you are writing a function that engages the landing gear of a plane. What do you do if the doors don't open? You don't just exit and log to the flight recorder so that the cleanup crew can find it. It's important that the landing gear sequence stops and this problem reported back to the cockpit so that the pilots can do something about it. It doesn't really matter which way it failed, you want to do the same thing: signal that there was an issue and what is known about it regardless of which function in that sequence failed.

This brings us back to ewan's answer. Don't catch exceptions that you can't resolve. Doing so defeats the purpose. The point is to let them bubble up to a point in your application where they can be handled appropriately. Often that means exiting abnormally and displaying an error message. By halting that bubble up routine prematurely, you aren't helping anyone, it just makes things worse.

🌐
Refine
refine.dev › blog › javascript-try-catch-finally
Error Handling With try, catch and finally Blocks in JavaScript | Refine
October 30, 2024 - In this article, we discussed in depth about graceful error handling in JavaScript using the try/catch/finally construct. We found out that putting our error-prone code inside a try {...} block allows us to catch any thrown exception.
🌐
Stack Overflow
stackoverflow.com › questions › 25733277 › proper-usage-of-try-catch-block-in-javascript
Proper usage of try/catch block in JavaScript - Stack Overflow
... You usually don't manually call throw. try/catch is generally used when a function you are calling might "throw" an error and you want to "catch" it. ... If you agree with @cdhowie you can simply disable this warning in Preferences.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-errors-throw-and-try-to-catch
JavaScript Errors Throw and Try to Catch - GeeksforGeeks
JavaScript uses throw to create custom errors and try...catch to handle them, preventing the program from crashing. The finally block ensures that code runs after error handling, regardless of success or failure.
Published   August 1, 2025
🌐
SmartBear Community
community.smartbear.com › smartbear community › testcomplete › testcomplete questions
javascript try/catch block | SmartBear Community
I thought try/catch blocks were supposed to help you avoid failures/exceptions. That is how they work in C# and from my understanding, this is how thye work in Javascript. Why is the below code still throwing an error? If it doesn't find the process called 'someProcess' the try/catch block should catch the error ...
Top answer
1 of 7
70

One should avoid throw errors as the way to pass error conditions around in applications.

The throw statement should only be used "For this should never happen, crash and burn. Do not recover elegantly in any way"

try catch however is used in situation where host objects or ECMAScript may throw errors.

Example:

var json
try {
    json = JSON.parse(input)
} catch (e) {
    // invalid json input, set to null
    json = null
}

Recommendations in the node.js community is that you pass errors around in callbacks (Because errors only occur for asynchronous operations) as the first argument

fs.readFile(uri, function (err, fileData) {
    if (err) {
        // handle
        // A. give the error to someone else
        return callback(err)
        // B. recover logic
        return recoverElegantly(err)
        // C. Crash and burn
        throw err
    }
    // success case, handle nicely
})

There are also other issues like try / catch is really expensive and it's ugly and it simply doesn't work with asynchronous operations.

So since synchronous operations should not throw an error and it doesn't work with asynchronous operations, no-one uses try catch except for errors thrown by host objects or ECMAScript

2 of 7
35

Try/catch in Javascript is not as bullet-proof as in other languages, due to Javascript's asynchronous nature. Consider this snippet:

try {
    setTimeout(function() {
        do_something_that_throws();
    }, 1000);
}
catch (e) {
    alert("You won't see this!");
}

The problem is that the control flow leaves the try block before do_something_that_throws() gets executed, so the error thrown inside the callback never gets catched.

So try/catch is basically inappropriate in many cases, and it's not always obvious whether something executes code asynchronously or not. Fortunately, javascript with its peculiar single-threaded-asynchronous-callback idiom and its support for actual closures provides an elegant alternative: continuation-passing style error handling. Just pass the proper response to any error as a function, e.g.:

setTimeout(function () {
    do_something_that_calls_err(function(err) {
        alert("Something went wrong, namely this: " + err);
    }),
    1000);
🌐
Meticulous
meticulous.ai › blog › javascript-try-catch-guide
JavaScript Try Catch | Complete Guide & Tutorial
Simply put, a try-catch statement consists of two blocks of code—one prefixed with the try keyword and the other with the catch keyword—as well as a variable name to store the error object within.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript try…catch
JavaScript try...catch
October 6, 2023 - Use the try...catch statement to handle exceptions in JavaScript. Place only the code that may cause an exception in the try block.
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_try_catch.htm
JavaScript - try...catch
The try-catch statement in JavaScript is used to handle the runtime errors (exceptions). This is very common in most programming languages to handle exceptions. A try-catch statement can handle only runtime errors. The try block must be followed by either exactly one catch block or one finally ...