Handle close and exit events