Exception Handling in JavaScript

Exception Handling in JavaScript

Exception handling in JavaScript, when done properly, can help maximize the maintainability, extensibility, and readability of your code. Errors are part of the programming journey. By producing errors, we actually learn how not to do something and how to do it better next time.

Errors are part of the programming journey. By producing errors, we actually learn how not to do something and how to do it better next time.

In JavaScript, when code statements are tightly coupled and one generates an error, it makes no sense to continue with the remaining code statements. Instead, we try to recover from the error as gracefully as we can. The JavaScript interpreter checks for exception handling code in case of such errors, and if there is no exception handler, the program returns whatever function caused the error.

This is repeated for each function on the call stack until an exception handler is found or the top-level function is reached, which causes the program to terminate with an error.

In general, exceptions are handled in two ways:

  1. Throw an exception — If there is a problem that can’t be handled meaningfully where it occurs at runtime, it’s best to throw it
function openFile(fileName) {
    if (!exists(fileName)) {
        throw new Error('Could not find file '+fileName); // (1)
  1. Catch an exception —  Thrown exceptions are caught and handled at the place where they make more sense at runtime
try {
} catch(e) {
// gracefully handled the thrown expection 

Let’s dive into these actions in more detail.

Throw an exception

If you’ve been using JavaScript for a long time, you may have seen something like ReferenceError: fs is not defined. This represents an exception that was thrown via a throw statement.


throw «value»;
// Don't do this
if (somethingBadHappened) {
    throw 'Something bad happened';

There is no restriction on the type of data that can be thrown as an exception, but JavaScript has special built-in exception types. One of them is Error, as you saw in the previous example. These built-in exception types give us more details than just a message for an exception.


The Error type is used to represent generic exceptions. This type of exception is most often used for implementing user-defined exceptions. It has two built-in properties to use.

1. message

This is what we pass as an argument to the Error constructor — e.g., new Error('This is the message'). You can access the message through the message property.

const myError = new Error(‘Error is created’)
console.log(myError.message) // Error is created

2. stack

The stack property returns the history (call stack) of what files were responsible for causing the error. The stack also includes the message at the top and is followed by the actual stack, starting with the most recent/isolated point of the error to the most outward responsible file.

Error: Error is created
at Object. (/Users/deepak/Documents/error-handling/src/index.js:1:79)
at Module.compile (internal/modules/cjs/loader.js:689:30)
at Object.Module.extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:266:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

Note: new Error('...') does not do anything until it’s thrown — i.e., throw new Error('error msg')   will create an instance of an Error in JavaScript and stop the execution of your script unless you do something with the Error, such as catch it.

Catch an exception

Now that we know what exceptions are and how to throw them, let’s discuss how to stop them from crashing our programs by catching them.


This is the simplest way to handle the exceptions. Let’s look at the syntax.

try {
    // Code to run
  } catch (e) {
    // Code to run if an exception occurs
  [ // optional
    finally {
      // Code that is always executed regardless of 
      // an exception occurring

In the try clause, we add code that could potentially generate exceptions. If an exception occurs, the catch clause is executed.

Sometimes it is necessary to execute code whether or not it generates an exception. Then we can use the optional block finally.

The finally block will execute even if the try or catch clause executes a return statement. For example, the following function returns false because the finally clause is the last thing to execute.

function foo() {
  try {
    return true;
  } finally {
    return false;

We use try-catch in places where we can’t check the correctness of code beforehand.

const user = '{"name": "Deepak gupta", "age": 27}';
try {
  // Code to run
  // In case of error, the rest of code will never run
} catch (err) {
  // Code to run in case of exception

As shown above, it’s impossible to check the JSON.parse to have the stringify object or a string before the execution of the code.

Note: You can catch programmer-generated and runtime exceptions, but you can’t catch JavaScript syntax errors.

try-catch-finally can only catch synchronous errors. If we try to use it with asynchronous code, it’s possible that try-catch-finally will have already been executed before the asynchronous code finishes its execution.

How to handle exceptions in an asynchronous code block

JavaScript provides a few ways to handle exceptions in an asynchronous code block.

Callback functions

With callback functions (not recommended) ,  we usually receive two parameters that look something like this:

asyncfunction(code, (err, result) => {
    if(err) return console.error(err);

We can see that there are two arguments: err and result. If there is an error, the err parameter will be equal to that error, and we can throw the error to do exception handling.

It is important to either return something in the if(err) block or wrap your other instruction in an else block. Otherwise, you might get another error — e.g., result might be undefined when you try to access result.data.


With promises — then or catch — we can process errors by passing an error handler to the then method or using a catch clause.

promise.then(onFulfilled, onRejected)

It’s also possible to add an error handler with .catch(onRejected) instead of .then(null, onRejected), which works the same way.

Let’s look at a .catch example of promise rejection.

  .then(res => {
      console.log(res) // 1
      throw new Error('something went wrong'); // exception thrown 
.then(res => {
      console.log(res) // will not get executed
.catch(err => { 
      console.error(err) // exception catched and handled

async and await with try-catch

With async/await and try-catch-finally, handling exceptions is a breeze.

async function() {
    try {
        await someFuncThatThrowsAnError()
    } catch (err) {
How to handle uncaught exceptions

Now that we have a good understanding of how to perform exception handling in synchronous and asynchronous code blocks, let’s answer the last burning question of this article : how do we handle uncaught exceptions?

In the browser

The method window.onerror() causes the error event to be fired on the window object whenever an error occurs during runtime. We can use this method to handle the uncaught exception.

Another utility mode for onerror() is using it to display a message in case there is an error when loading images in your site.

<img src="testt.jpg" onerror="alert('An error occurred loading yor photo.')" />

On a Node.js server

The process object derived from the EventEmitter module can be subscribed to the event uncaughtException.

process.on("uncaughtException", () => {})`

We can pass a callback to handle the exception. If we try to catch this uncaught exception, the process won’t terminate, so we have to do it manually.

The uncaughtException only works with synchronous code. For asynchronous code, there is another event called unhandledRejection.

process.on("unhandledRejection", () => {})

Never try to implement a catch-all handler for the base Error type. This will obfuscate whatever happened and compromise the maintainability and extensibility of your code.

Key takeaways

Let’s review some of the main points we discussed in this article.

  • The throw statement is used to generate user-defined exceptions. During runtime, when a throw statement is encountered, execution of the current function will stop and control will be passed to the first catch clause in the call stack. If there is no catch clause, the program will terminate
  • JavaScript has some built-in exception types, most notably Error, which returns the error stack and message
  • The try clause will contain code that could potentially generate an exception
  • The catch clause will be executed when exceptions occur
  • For asynchronous code, it’s best to use async-await with try-catch
  • An unhandled exception can be caught, which can prevent the app from crashing

When done properly throughout, exception handling can help you improve the maintainability, extensibility, and readability of your code.

Originally published by Deepak Gupta at https://blog.logrocket.com

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:


First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?


I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI