Node.js Try Catch

Node.js Try Catch is an Error Handling mechanism. When a piece of code is expected to throw an error and is surrounded with try, any exceptions thrown in the piece of code could be addressed in catch block. If the error is not handled in any way, the program terminates abruptly, which is not a good thing to happen.

Note : It is a good practice to use Node.js Try Catch only for synchronous operations. We shall also learn in this tutorial as to why Try Catch should not be used for asynchronous operations.

Example of Node.js Try Catch

In this example, we shall use a Try Catch around the piece of code that tries to read a file synchronously.

When the above program is run..

Observe that the program did not terminate abruptly, but continued with the execution of subsequent statements.

Now we shall see what happens if we do not use try catch for the same operation above.

There is no error handling mechanism incorporated in the code. And the program terminates abruptly and the subsequent statements are not executed.

When the above program is run..


Why Node.js Try Catch should not be used for catching errors in Asynchronous Operations

Consider the following example where we try to read a file asynchronously with a callback function and throw an error if something goes wrong. And we surround the task with a Try Catch Block, hoping to catch the error thrown.

If you observe the output,console.log("Next Statements")  has been executed prior to if(err) throw err  which is because, reading file is being done asynchronously and the control does not wait the file operation to complete, instead it proceeds with the next statement. Which means, the control is out of try catch block. If an error occurs during the asynchronous operation, there is no try catch block the control could know of. Hence our Try Catch block cannot catch errors that could occur during asynchronous operations and developers should avoid catching errors thrown by asynchronous tasks with Node.js Try Catch blocks.


What happens to exceptions in asynchronous code ?

If you are puzzled as to what happens to exceptions in asynchronous code, here is the answer. If you have gone through Callback Function, and observed an error object as an argument, this is where any errors or exceptions are reported back to Node.js.


Conclusion :

In this Node.js TutorialNode.js Try Catch, we have learnt the scenarios where to use Try Catch, and where not to use it.