Hacker News new | ask | show | jobs
by rvkennedy 4667 days ago
His argument is really against using exceptions as part of normal operation, which I agree with. I've noticed when writing plugins to big monolithic programs like 3DS Max and game engines that these tend to throw and catch exceptions as a matter of course, which is a pain when you're trying to debug your own plugin code.

An exception should mean "normal operation cannot continue", and should signify a bug in your code. As such, it is an exceptionally good software development tool.

3 comments

Exceptions aren't a debugging tool. You should use asserts for debugging. These asserts are then disabled via compile switches for the production version. Or you can write unit tests.
I agree. Exceptions are a very useful tool, when used appropriately. Problem is, they're not used very appropriately.
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)

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.