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". Answer from theScottyJam on reddit.com
🌐
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 ...
🌐
W3Schools
w3schools.com › js › js_errors.asp
JavaScript Error Statements
The try block contains the code that might throw an error. ... The catch block executes only if an error occurs in the try block.
Discussions

How often do you use Try/Catch blocks in your JS code?
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". More on reddit.com
🌐 r/learnjavascript
16
3
February 12, 2023
exception - Understanding try..catch in Javascript - Stack Overflow
I have this try and catch problem. I am trying to redirect to a different page. But sometimes it does and some times it doesnt. I think the problem is in try and catch . can someone help me underst... More on stackoverflow.com
🌐 stackoverflow.com
Handling specific errors in JavaScript (think exceptions) - Stack Overflow
Following is the exceedingly stupid ... using the throw statement, and caught outside the try block with a catch statement." 2012-10-14T16:46:08.193Z+00:00 ... Well Microsoft's C# certainly handles errors better than Javascript :P.... More on stackoverflow.com
🌐 stackoverflow.com
Javascript error handling with try .. catch .. finally - Stack Overflow
9 How does a try..finally for loop with continue work in JavaScript? -9 Equivalent of try catch(exception handling) in JavaScript More on stackoverflow.com
🌐 stackoverflow.com
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › error handling
Error handling, "try...catch"
First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping 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.
Top answer
1 of 2
24

I think your main problem is that you're swallowing exceptions, which is very bad. This is why "it works sometimes". Something is throwing an exception, and you're catching it, but then you're not doing anything else after that. At the very least I would display some sort of error message in your catch block.

A few other problems:

  • Are you sure you need those multiple try..catch blocks? The current assumption in your code is that each line that is wrapped in a try..catch is independent of the others, and execution can still proceed if something goes wrong in any one (or more) of those statements. Are you sure this is what you want? If so, there is definitely a better way of handling this.
  • If the statements are not independent of each other, and if a failure at any point means that execution cannot proceed, then you can wrap all of those statements in a single try..catch block and display an error message in the catch
  • Like I said before, swallowing exceptions is very bad! You're hiding the problem and not achieving anything. It also makes debugging extremely hard, because things will stop working and you will have no idea why (no exception, no logging, no error messages). Exceptions are used when something unexpected happens that interrupts normal program flow. It is something you definitely want to handle.

I think what you want can be done this way:

try {
    if(window.opener.hideRecordReload){
        window.opener.hideRecordReload(pg.recordID, pg.recordTypeID);

    } else {
        window.opener.pg.hideRecord(pg.recordID, pg.recordTypeID);

    }

    window.opener.pg.hideEncounter(pg.recordID);
    window.opener.pg.hideRecordResponse(pg.hideReasonID.value == 0 ? pg.otherReason.value : pg.hideReasonID.options[pg.hideReasonID.selectedIndex].text);
    window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
    window.opener.pg.hideRecord_Response(pg.recordID, pg.recordTypeID);
    window.opener.window.parent.frames[1].pg.loadQualityMeasureRequest();
    window.opener.pg.closeWindow();

}

catch(e) {
   console.log(e);
}   

This way, if an exception occurs anywhere along those series of statements, the catch block will handle it.

Javascript also doesn't have true checked-exceptions. You can get around it by having a single try block, and inspecting the exception object that you receive*.

Expanding on what I talked about earlier, there are two ways of handling exceptions. The first way, like I showed earlier, assumes that when an exception happens, the code is in an invalid/undefined state and this therefore means that the code encountered an unrecoverable error. Another way of handling exceptions is if you know it is something you can recover from. You can do this with a flag. So:

try {
   doSomething();
}

catch(e) {
   error = true;
}

if(error) {
   doStuffToRecoverFromError();
}

else {
   doOtherStuff();
}

In this case the flow of your logic depends on an exception being thrown. The important thing is that the exception is recoverable, and depending on whether it was thrown or not, you do different things.

*Here is a somewhat contrived example that demonstrates checked-exceptions. I have two exceptions called VeryBadException and ReallyBadException that can be thrown (randomly) from two functions. The catch block handles the exception and figures out what type of exception it is by using the instanceof operator):

function VeryBadException(message) {
   this.message = message; 
}

function ReallyBadException(message) {
   this.message = message;
}

function foo() {
   var r = Math.floor(Math.random() * 4);
   if(r == 2) {
      throw new VeryBadException("Something very bad happened!");
   }
}

function bar() {
   var r = Math.floor(Math.random() * 4);
   if(r == 1) {
      throw new ReallyBadException("Something REALLY bad happened!");
   }
}

try {
  foo();
  bar();
}

catch(e) {
   if(e instanceof VeryBadException) {
      console.log(e.message);
   }

   else if(e instanceof ReallyBadException) {
      console.log(e.message);
   }
}
2 of 2
4

It's good practice do something with the caught exceptions.

What's happening here is that if there's an error (say loading a page fails) an exception is thrown inside one of your try blocks. The corresponding catch block grabs it and says "that exception has been dealt with" but in actuality you've not done anything with it.

Try putting a print(e.Message); inside your catch blocks to find out exactly what error is causing the page not to load and then add code to your catch block to deal with this error.

🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Control_flow_and_error_handling
Control flow and error handling - JavaScript | MDN
September 19, 2025 - The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown.
Find elsewhere
🌐
DEV Community
dev.to › ycmjason › stop-hating-try-catch-in-javascript-just-use-this-pattern-5b92
TRY {} CATCH {} ‒ FIXED! (with a surprisingly old trick) - DEV Community
May 11, 2025 - It keeps things local and avoids the weird side effects of broad try-catch blocks. If it ever feels messy, you can always extract it into a function and give it a name. I usually only do that when I actually need to reuse the error handling. (Which is also a nice way to reuse logic without abstracting too early, you know, naming is hard.) Curious — have you used IIFE in your projects before, or is this your first time seeing it used like this? ... I cook delicious TypeScript / JavaScript nuggets.
🌐
Medium
medium.com › weekly-webtips › functional-try-catch-in-javascript-8b9923c3e395
Functional Try-catch In JavaScript | by JM Santos | Webtips | Medium
July 20, 2021 - In the second example, where we go through the rabbit hole of the try-catch statement, the issue that I see there is having to put everything inside a try-catch just for a special function that throws an error. If you’re working with a function that throws an error, you have no choice but to move all your logic inside of it which I don’t like.
🌐
W3Schools
w3schools.com › jsref › jsref_try_catch.asp
JavaScript try/catch/finally Statement
JavaScript creates an Error object with two properties: name and message. The try...catch...finally statements combo handles errors without stopping JavaScript.
🌐
Medium
medium.com › @kaklotarrahul79 › master-javascript-error-handling-try-catch-finally-explained-with-examples-b928a5af8204
Master JavaScript Error Handling Try Catch Finally Explained with Examples | by Rahul Kaklotar | Medium
February 8, 2025 - class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } try { throw new ValidationError("Invalid input!"); } catch (error) { console.log(error.name + ": " + error.message); } 📌 Custom errors help organize and identify specific types of errors. ... Error handling is essential for writing robust JavaScript applications.
🌐
YouTube
youtube.com › watch
I'm Ditching Try/Catch for Good! - YouTube
The try/catch block is a staple of JavaScript, but it leaves a lot to be desired (especially when working with TypeScript). None of the errors are typed, it ...
Published   October 15, 2024
🌐
freeCodeCamp
freecodecamp.org › news › try-catch-in-javascript
Try/Catch in JavaScript – How to Handle Errors in JS
December 30, 2020 - One of the benefits of try/catch is its ability to display your own custom-created error. This is called (throw error). In situations where you don't want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement.
🌐
Reddit
reddit.com › r/javascript › how is 'try/catch' useful?
r/javascript on Reddit: How is 'try/catch' useful?
November 3, 2014 -

I feel like I understand JavaScript quite well but I've never been able to grasp why I would use try/catch in any script that I write.

Any time I'd like to investigate anything in my script I just use the console and always seem to figure things out pretty quickly since the developer tools tend to show me exactly what went wrong and at what line. So what does try/catch have to offer?

I've looked into try/catch and it seems to just allow me to print a customized error message on the screen rather than the console using whatever script I write in the block and the catch argument. Ok.

How would this be useful? This seems mostly useless.

So I write custom error messages in my document window rather than just viewing them in my console. Why would I even want to do that? If I want to know basically anything and everything about a particular error it just shows up in the console.

I have yet to read a site that even explains why I would want to use this I only find sites that tell me how to do it. Can anyone clarify this for me? Thanks.

Top answer
1 of 5
28
The point of try/catch is not to make it easier for you to debug errors. It's so you can recover from errors. It's not a developer tool for tracking down bugs, it's a way of writing code that doesn't have bugs in the first place. The idea being that instead of your code just crashing, it can recover from something going wrong. This is a much better experience for your end users.
2 of 5
4
I think that most of the other answers on this page are failing to explain the whole "What's the point?" or "What problem is try/catch trying to solve?". I'll try to keep it simple. Things go wrong in code. Maybe you tried to read a file and the file wasn't there. Or your function expects a string parameter to contain the name of a user, but your code couldn't find the user requested. When things go wrong, or programs should handle the situation in a graceful way, and not just blow up. Traditionally, if something goes wrong inside a function you might return a special value or error code to indicate that an error occurred. For example, our function getUserInfo(name_string) may return null if there is an error, or it may return an object with fields "info", and "status_code". The status code could indicate if the requested user is missing, or maybe if the caller doesn't have permission etc etc. Someone using our getUserInfo() function should then examine status code first to if the call was successful. result = getUserInfo(someUserName); if (result.status_code !== SUCCESS) { // something went wrong. log(...); // Maybe report the exact error to the user. return; } ... // run normally. If every time that you use a function you also have to check its status code, you can imagine that your code becomes a mess with error handling code mixed in with the code that runs normally (i.e. what you are really trying to do). "Exceptions" are a mechanism which allows you to separate error handling from the normal successful code path. If something in getUserInfo() goes wrong, then it can throw an exception and the caller can then catch it using try/catch. The exception object itself can contain more detailed information about the exact error. try { ... userObj = getUserInfo(someUserName); ... ... // normal execution is here. ... } catch (ex) { // something went wrong. Log it or do something. ... } Your own code can throw exceptions to communicate errors to callers. That is the point. It is a way of handling errors in code in a structured and clear way. Other details: Often you want one try/catch to cover a series of related function calls which could go wrong, and to handle the errors the same way. Many functions in the browser and libraries use exceptions already. When an exception is thrown the JS will exit the function and keep on returning from the functions on the stack until it finds a try/catch which will accept and handle the thrown exception. People don't use exception very much in the JS code I've seen.
🌐
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.
🌐
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.
Published   August 1, 2025
Top answer
1 of 2
7

There are two primary problems with that code:

  1. You have a typo: var myErro = err; is missing the r on the end of myErro.

  2. You're trying to use err in the finally block, but it's only in scope in the catch block.

...and then a few more that don't match what it seems like the assignment is telling you to do

  1. You're not doing #1, you're doing something else which coincidentally also tries to use myVar

  2. You don't have any code implementing #6.

  3. Your code assigning result when there's an error is putting myErrorName and myErrorMessage literally in the string, rather than using the values of those variables.

  4. Your message for when no errors have occurred is not the same as the message they told you to use, it has slight differences (including a typo). Programming is at least partially about attention to detail. :-)

You don't need if (myError == err), just if (myError) will do:

try{
  myVar();
}
catch(err){
  var myError = err;
  var myErrorName = err.name;
  var myErrorMessage = err.message;
}
 finally{
  if(myError){
    var result = "There was an error (myErrorName:myErrorMessage)";
    console.log(result);
 }else{
    console.log("No error ocurred");
 }
}

(I added a console.log so we'd see the error case.)

I've only addressed #1 and #2 in the above, the rest are left as an exercise for you to complete. :-)


I should note that I wouldn't write it that way. Declaring a variable in the catch block that you use in the finally block does work, with var (because var is not block-scoped and is hoisted), but it's misleading to people trying to maintain the code. If you're going to use a variable in both of those blocks, move the declaration outside the blocks for clarity.

2 of 2
0

Check this It will work

try{
  console.log(myVar);
}
catch(err){
  var myError = err;
  var myErrorName = err.name;
  var myErrorMessage = err.message;
}
 finally{
  if(myError){
    var result = "There was an error ("+ myErrorName+": "+myErrorMessage+")";
 }else{
   result = "No error ocurred";
 }
}
Top answer
1 of 4
86

Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.

If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch:

function tryCatch(fun) {
    try {
        return fun();
    }
    catch(e) {
        tryCatch.errorObj.e = e;
        return tryCatch.errorObj;
    }
}
tryCatch.errorObj = {e: null};


var result = tryCatch(someFunctionThatCouldThrow);
if(result === tryCatch.errorObj) {
    //The function threw
    var e = result.e;
}
else {
    //result is the returned value
}

After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch is the same as that of normal code.

2 of 4
72

The original question asked about the cost of try/catch when an error was not thrown. There is definitely an impact when protecting a block of code with try/catch, but the impact of try/catch will vanish quickly as the code being protected becomes even slightly complex.

Consider this test: http://jsperf.app/try-catch-performance-jls/2

A simple increment runs at 356,800,000 iterations per second The same increment within a try/catch is 93,500,000 iterations per second. That's on overhead of 75% due to try/catch. BUT, a trivial function call runs at 112,200,000 iterations per second. 2 trivial function calls run at 61,300,000 iterations per second.

An un-exercised try in this test takes slightly more time than one trivial function call. That's hardly a speed penalty that matters except in the inner-most loop of something really intense like an FFT.

The case you want to avoid is the case where an exception is actually thrown. That is immensely slower, as shown in the above link.

Edit: Those numbers are for Chrome on my machine. In Firefox there is no significant difference between an unexercised try and no protection at all. There's essentially zero penalty to using try/catch if no exception is thrown.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Promise › try
Promise.try() - JavaScript | MDN
July 10, 2025 - function doSomething(action) { return Promise.try(action) .then((result) => console.log(result)) .catch((error) => console.error(error)) .finally(() => console.log("Done")); } doSomething(() => "Sync result"); doSomething(() => { throw new Error("Sync error"); }); doSomething(async () => "Async result"); doSomething(async () => { throw new Error("Async error"); });