My question is: how to prevent the program from crashing, even if the error happens?
If the error happens, the program continues to run, and no longer accepts more connections until the number of open files decreases. In many programas an error occurs and raise an exception, but the program continues to run, don't crash!