# Uncaught Exceptions & Process Events — Node.js

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

> The last line of defense when something escapes every catch.

## 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
- [x] Log it and exit the process
- [ ] Retry the failed operation automatically

*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.
