English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

NodeJS Other

Node.js Try Catch

Node.js Try Catch It is a mechanism for error handling. When a piece of code is expected to throw an error and is enclosed in a try block, any exceptions thrown within the code segment can be resolved in the catch block. If errors are not handled in any way, the program will suddenly terminate, which is not a good thing.

Note: It is best toNode.js Try CatchIt is only used for synchronous operations. We will also learn in this tutorial why it is not recommended toTry Catchfor asynchronous operations.

  • Node.js example of attempting to catch

  • Why Not Use Node.js Try Catch to Catch Errors in Asynchronous Operations

  • What will happen to exceptions in asynchronous code?

Node.js example of attempting to catch

In this example, we will be usingAttemptused around the code segment for synchronous file reading.Try Catch.

#example for Node.js Try Catch
var fs = require('fs'); 
 
try{ 
    // File does not exist
    var data = fs.readFileSync('sample.html'); 
 } catch (err) { 
    console.log(err); 
 } 
 
console.log("Continuing with other statements...");

When the above program runs...

Terminal Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example.js  
 { Error: ENOENT: no such file or directory, open 'sample.html'
    at Object.fs.openSync (fs.js:652:18) 
    at Object.fs.readFileSync (fs.js:553:33) 
    at Object.<anonymous> (/nodejs/nodejs-try-catch-example.js:5:16) 
    at Module._compile (module.js:573:30) 
    at Object.Module._extensions..js (module.js:584:10) 
    at Module.load (module.js:507:32) 
    at tryModuleLoad (module.js:470:12) 
    at Function.Module._load (module.js:462:3) 
    at Function.Module.runMain (module.js:609:10) 
    at startup (bootstrap_node.js:158:16) 
  errno: -2, 
  code: 'ENOENT', 
  syscall: 'open', 
  path: 'sample.html'} 
Continuing with other statements..

Please note that the program does not terminate abruptly but continues to execute the subsequent statements.

Now, let's see what happens if we do not use try catch for the same operation above.

# error without Node.js Try Catch
var fs = require('fs'); 
 
// Attempt to read the file synchronously instead of presenting the file
var data = fs.readFileSync('sample.html'); 
 
console.log("Continuing with other statements...");

The code does not have an error handling mechanism, and the program terminates abruptly, and the subsequent statements do not execute.

When the above program runs...

Terminal Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example-1.js  
/home/arjun/nodejs/nodejs-try-catch-example-1.js:1
 (function (exports, require, module, __filename, __dirname) { # example for Node.js Try Catch
                                                              ^
 
SyntaxError: Invalid or unexpected token
    at createScript (vm.js:74:10) 
    at Object.runInThisContext (vm.js:116:10) 
    at Module._compile (module.js:537:28) 
    at Object.Module._extensions..js (module.js:584:10) 
    at Module.load (module.js:507:32) 
    at tryModuleLoad (module.js:470:12) 
    at Function.Module._load (module.js:462:3) 
    at Function.Module.runMain (module.js:609:10) 
    at startup (bootstrap_node.js:158:16) 
    at bootstrap_node.js:598:3

Why Not Use Node.js Try Catch to Catch Errors in Asynchronous Operations

Consider the following example, in which we attempt to asynchronously read a file using a callback function and throw an error if an issue occurs. Then, we wrap the task with a 'try to catch' block, hoping to catch the thrown error.

# Node.js Try Catch with Asynchronous Callback Function
var fs = require('fs'); 
 
try{ 
    fs.readFile('sample.txta', 
        // Callback Function
        function(err, data) {  
            if (err) throw err; 
    }); 
 } catch(err){ 
    console.log("In Catch Block") 
    console.log(err); 
 } 
console.log("Next Statements")

Terminal Output

arjun@arjun-VPCEH26EN:~/nodejs/try-catch$ node nodejs-try-catch-example-2.js  
Next Statements
/home/arjun/nodejs/try-catch/nodejs-try-catch-example-2.js:8
            if (err) throw err; 
                     ^
 
Error: ENOENT: no such file or directory, open 'sample.txta'

If you observe the output, pleaseconsole.inif(err)  throw  errhas been executed beforelog("Next Statements"  This is because, reading the file is completed asynchronously, and the control does not wait for the file operation to complete, but continues to execute the next statement.This means that the control is not within the try catch block.If an error occurs during asynchronous operations, the control will not know any try catch block.Therefore, our Try Catch block cannot capture errors that may occur during asynchronous operations, and developers should avoid using it.Node.js Try CatchBlockCaptureErrors caused by asynchronous tasks.

What will happen to exceptions in asynchronous code?

If you are confused about what will happen to exceptions in asynchronous code, this is the answer. If you have passed a Callback function and observed the error object as a parameter, then here all errors or exceptions are reported back to Node.js.

Summary:

In this Node.js tutorial – Node.js Try CatchWe learned about using Try Catch and scenarios where it is not used.