What happens when an uncaught exception occurs in Node.js?
If an error (exception) is thrown but not caught, Node.js will:
- Print the error stack trace to the console.
- Immediately terminate the process to avoid unpredictable behavior.
Why? Because an uncaught exception might leave the app in an inconsistent state.
Best practice: Use try/catch for synchronous code, and listen to
'uncaughtException' or 'unhandledRejection' events to log errors and gracefully
shut down:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1); // Exit to avoid unstable state
});