What is the difference between process.exit() and throwing an uncaught exception?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
Answer
process.exit(code) immediately terminates the Node.js process with the given exit code (0 = success, non-zero = error). It bypasses the normal event loop drain — pending callbacks, I/O operations, and promises are abandoned. Before calling process.exit(), emit a "beforeExit" event yourself or use process.exitCode property (lets the event loop drain naturally first). Use process.exit() explicitly only in CLI tools after completing work, or in fatal error handlers after cleanup. Throwing an uncaught exception (an exception not caught by any try/catch) triggers the uncaughtException event on process. If no listener is registered, Node.js prints the stack trace and exits with code 1. If you register a listener, the process can continue (but the application is in an undefined state — this is dangerous). The recommended pattern: listen to uncaughtException and unhandledRejection for logging/cleanup, then call process.exit(1). Do not attempt to continue after uncaught exceptions. For Promise rejections: unhandledRejection will cause process exit by default in Node.js 15+.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Node.js codebase.
Previous
What are memory leaks in Node.js and how do you detect them?
Next
What is the N+1 query problem and how do you solve it in Node.js?
More Node.js Questions
View all →- Advanced How does Node.js handle concurrency without multiple threads?
- Advanced What is the Node.js memory model and how does garbage collection work?
- Advanced What are memory leaks in Node.js and how do you detect them?
- Advanced What is the N+1 query problem and how do you solve it in Node.js?
- Advanced What is circuit breaking pattern in Node.js microservices?