1

I wonder if the below python code (specifically http server) ever crashes? Assuming that there is no grammer error in any of the library code(already compiled), what I think that handling the exceptions in a while loop should be sufficient for this code not to crash anytime. I tried the below code for a while and never crashed, but I wonder if theoretically or practically possible for this program to crash?

while True:
    try:

        server = HTTPServer(('', PORT_NUMBER), myHandler)
        server.serve_forever()

    except:
        try:
           server.socket.close()
        except:
            pass

The actual reason I am asking this question that I don't want to deal with UNIX staff to watch the process and restart it if it crashes. Is the above solution sufficient? Thanks.

5
  • 1
    Socket.close() could raise an exception in some edge cases. Commented Mar 31, 2020 at 6:20
  • @KlausD. Can you give an example of such a case? Commented Mar 31, 2020 at 6:33
  • 1
    The Socket has been closed by the OS for any reason. Commented Mar 31, 2020 at 6:37
  • I edited to code in question, so please forget about server.socket.close() line Commented Mar 31, 2020 at 6:48
  • While you will now stay inside the loop, it is not guaranteed that the code really works. If it raises an exception it will be stuck in a loop without ever working. And no tool (like supervisord explained below) will notice. It will most likely just occupy one CPU core. Commented Mar 31, 2020 at 6:52

2 Answers 2

0

If "except" block has worng code, it can crash cause of it. I mean, something like that:

# path/to/py3
FOO = [1,2,3]
try:
  # index out of bound, try block has error, so it goes ahead and executes except-block
  print(FOO[4])
except:
  # if there is some kind of error, like Syntax error, program can crash
  print "Index out of bound!"
  print("2"+2)
  print(FOO["BAR"])

but if exception block has the correct logic too, then programm should work without crashing

Sign up to request clarification or add additional context in comments.

1 Comment

Except clause has only this line and one can assume it never throws: server.socket.close()
0

Like Klaus D. already mentioned in his comment, there can be cases where the socket close code in your except block crashes. You could optionally also throw a try except around that as well...

Another option is to use something like this (no UNIX involved):

http://supervisord.org/

It's easy to run and will automatically restart your program if it crashes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.