Better exception handling to prevent deadlocks