Pop return from stack?

Carl Banks pavlovevidence at gmail.com
Mon Aug 16 01:44:48 EDT 2010


On Aug 15, 6:43 pm, bvdp <b... at mellowood.ca> wrote:
> On Aug 15, 12:52 pm, John Nagle <na... at animats.com> wrote:
>
>
>
> > On 8/14/2010 4:05 PM, bvdp wrote:
>
> > > Assuming I have a module 'foo.py' with something like this:
>
> > > def error(s):
> > >      print "Error", s
> > >      sys.exit(1)
>
> > > def func(s):
> > >      ... do some processing
> > >      ... call error() if bad .. go to system exit.
> > >      ...  more processing
>
> >     Fix "func".  That's terrible Python.   No standard Python library
> > module calls system exit to handle an error.  So that must be in
> > your code.   Standard procedure for errors is to raise an
> > exception.
>
> Not to belabor the point .. but "func" is not a standard lib module.
> It's part of a much larger application ... and in that application it
> makes perfect sense to terminate the application if it encounters an
> error. I fail to see the problem with this. Why would an APPLICATION
> raise a error or not exit to the system?
>
> Does it help to note that error() as defined in the application prints
> out a helpful message, etc?
>
> The whole problem I was having is that I was trying to tie a small
> application (an helper to the main application) to use a bit of the
> existing code as a pseudo-library. Certainly, if the code I was
> interfacing with was a standar Python module ... well, then this
> thread would not exist in the first place.
>
> However, I have gotten hit with more than one comment like yours. So,
> could you please clarify? Is it bad form to exit an application with
> sys.exit(1) when an error in a file the application is processing is
> found?
>
> Honestly, I'm not trying to be argumentative ... just trying to
> understand.

The One Obvious Way to handle errors in Python is to raise an
exception, and catching it wherever you can proceed.  If you can't
proceed, either don't catch it, or catch it at the top level.  Example
(Python 2.6):


class MyException(Exception):
    pass


def some_function deep in call tree():
    # do some stuff
    if is_error():
        # will be caught way up the stack, in main
        raise MyException(error_message)
    # do some stuff if there wasn't an error


def main():
    try:
        run_program()
    except MyException as exc:
        print >> sys.stderr, str(exc)
        sys.exit(1)


If you call sys.exit() deep within your call tree, the world won't
come to an end, but raising an exception is the preferred way to do
it.

FWIW, I think it perfectly reasonable to let an application print a
traceback on an error.  I've gotten a few bug reports on a little tool
I maintain where the user copies the traceback to me, it it's helped
me diagnose their issues a lot.


Carl Banks



More information about the Python-list mailing list