Which exception to use?

Tim Evans t.evans at paradise.net.nz
Thu Jan 30 03:42:31 EST 2003


"Bjorn Pettersen" <BPettersen at NAREX.com> writes:

> > From: Edward C. Jones [mailto:edcjones at erols.com] 
> > 
> > Which exception is it best to use in the following pieces of code?
> > 
> > if len(sys.argv) != 2:
> >      raise SomeException, 'program requires exactly one argument'
> 
> Do you really want a traceback in this case?...
> 
>   print >> sys.stderr, 'program requires exactly one argument'
>   sys.exit(1)
> [snip]

I think that you would be better off writing that as:

  sys.exit('program requires exactly one argument')

Or the equivalent form (that I prefer):

  raise SystemExit('program requires exactly one argument')

In the usual case, the end result is still the same: print the message
to stderr and exit with status 1.  The difference is if the SystemExit
exception is caught the message is available to the exception handler,
not just written to stderr.  This might become useful if you implement
a GUI/CGI/... program and want to display errors in a different way.

-- 
Tim Evans





More information about the Python-list mailing list