exceptions == errors?

Alexander Schmolck a.schmolck at gmx.net
Tue Apr 8 02:16:06 CEST 2003


Mark Harrison <mh at pixar.com> writes:

> Are exceptions always considered errors, or there the same feeling
> as in C++ that exceptions can be used for non-error situations?

No. Yes: iterators raise an StopIteration exception to signal that there are
no more elements left. Thus

  for x in container: print x
  print "done"

will print xs until a StopIteration is raised by the iterator returned by
container's __iter__ method, at which point execution quietly continues with
the ``print "done"`` statement.

> 
> I am asking because I am writing a network server that has the
> general outline
> 
> 	while 1:
> 		read request
> 		process request
> 		send response
> 
> So, I have the option to
> 
> 1.  embed the "send response" code in the request processing code

Sounds somehow bad.

> 
> 2.  Have the request processing code generate formatted responses
>     that are returned to the main loop
> 
> As is usually the case, adding robust error checking and reporting
> throws a kink into the works.   I have to do a lot of exception
> wrapping in the request processing code in order to ensure that
> there are no code paths where an exception short-circuits a
> response generations.
> 
> Therefore, I'm thinking of structuring the code like this:
> 
> 	while 1:
> 		try:
> 			read request
> 			process request
> 		catch MyException,e:
> 			send response contained in e
> 		catch Exception,e:
> 			send "internal error" response
> 
> Am I setting myself up for trouble if I follow this route?
> All advice gratefully received.


I don't fully understand your problem from your description, but maybe you
want some variation on this?


try: 
    # you'll likely want try: except: statements nested in here for error
    # handling
    read request
    process request
# irrespective of whether an error occured send a response
finally:
    send response



'as




More information about the Python-list mailing list