Hacker News new | ask | show | jobs
by smtddr 4673 days ago
I got a question. Do you think it's okay use exceptions to end what would be otherwise an infinite loop? Python example:

  data = ""
  socket.settimeout(1.5)
  while 1:
    try:
      data += socket.recv(1024)
    except Exception,e:
      store_data(data)
      break
If this is not okay, what would you change?

(And yes, I know there are edge'ish cases were I'd miss some data here)

3 comments

This is NOT OK. You're swallowing all exceptions and assuming that they are your special case.

The fix is to have a specific nonambiguous name for your exception, so that other error conditions still work properly. As examples consider the StopIteration and GeneratorExit exceptions from Python's standard library. (See http://docs.python.org/2/library/exceptions.html for a list of built-in exceptions.)

Exceptions for control flow are a slippery slope. in the socket case, it would be better to parse a terminator frame from your recieved data and just do socket.close() like normal than to hack a timeout or internal socket close, or negociate a fixed transmission length in advance.

This is on the basis code like this is hard to debug, moreso than any glorious exception free master style. You aren't guaranteed to have recieved your entire transmission in your exception block because you are catching any recieve exception. You do want exception handling here, but not as control flow, you want it as damage control if you get an unexpected early termination, not when you get desired behavior.

It would be okay as an optimisation in a very hot spot in your code, after a lot of benchmarking. I would frown upon using that as a general practice.