# Uncaught Exceptions & Process Events — Node.js Fundamentals: Modules, Async and Servers

Source: https://www.skillbyai.com/en/nodejs/node-uncaught-exceptions

> Handle uncaughtException and process exit events as a last line of defence: log, then exit cleanly.

## uncaughtException

Listen for exceptions that escape all your `try/catch` blocks — use it to log and exit cleanly, not to keep running.

```javascript
process.on("uncaughtException", (err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});

process.on("unhandledRejection", (reason) => {
  console.error("Unhandled rejection:", reason);
  process.exit(1);
});
```

## The exit event

`process.on("exit", ...)` fires right before Node shuts down — good for final synchronous cleanup, but no async work runs there.

**Quiz:** Once uncaughtException fires, what's the recommended action?

- [ ] Ignore it and continue
- [ ] Retry the failed operation automatically
- [x] Log it and exit the process
- [ ] Silence all errors with an empty handler

*Answer:* Log it and exit the process. After an uncaught exception, app state may be corrupted — log the error and exit rather than limping along.
