The ‘uncaughtException’ is an event of class Process within the processing module which is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop.
Syntax:
Event: 'uncaughtException'
Parameters: This event does not accept any argument as a parameter.
Return Value: This event returns nothing but a callback function for further operation.
Example 1:
// Node.js program to demonstrate the // Process 'uncaughtException' Event // Importing the modules const process = require( 'process' );
var fs = require( 'fs' );
// Independent Block which will execute setTimeout(() => { console.log( '\n' )
console.log( 'Greetings from GeeksforGeeks' );
}, 1000); // Event 'uncaughtException' process.on( 'uncaughtException' , (error, source) => {
fs.writeSync(process.stderr.fd, error, source); }); // Throwing an exception nonexistentFunc(); console.log( 'This Block of code will not run' );
|
Run the index.js file using the following command:
node index.js
Output:
ReferenceError: nonexistentFunc is not defined Greetings from GeeksforGeeks
Example 2:
// Node.js program to demonstrate the // Process 'uncaughtException' Event // Importing the modules const process = require( 'process' );
const fs = require( 'fs' );
// Event 'uncaughtException' process.on( 'uncaughtException' , (error) => {
fs.writeSync(process.stderr.fd, error);
}); // Throwing our Error throw new Error( 'Ran out of coffee' )
|
Run the index.js file using the following command:
node index.js
Output:
Error: Ran out of coffee
Reference: https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_uncaughtexception