Pop return from stack?
pavlovevidence at gmail.com
Mon Aug 16 07:44:48 CEST 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
> Honestly, I'm not trying to be argumentative ... just trying to
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
def some_function deep in call tree():
# do some stuff
# will be caught way up the stack, in main
# do some stuff if there wasn't an error
except MyException as exc:
print >> sys.stderr, str(exc)
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
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.
More information about the Python-list