[Tutor] Treating program exceptions

Reisfeld, Brad CAR Brad.Reisfeld@carrier.utc.com
Fri, 5 Oct 2001 09:45:51 -0400


Hi,
I am wondering about the best way to flag out errors to my program's users
or calling programs. 

Possible as a holdover from my shell programming experience, I currently do
something like the following:
---
(OKAY, NUM_PARAM_ERR, INVALID_PROP_ERR, DUP_PROP_ERR, INVALID_VAL_ERR,
OUT_OF_B\
OUNDS_ERR, EMPTY_FILE_ERR, OUTPUT_ERR) = range(8) 

arg_list = sys.argv
prog_name = os.path.basename(arg_list.pop(0)) 

if num_args != 6 and num_args != 4:
    print "Error: Improper number of arguments."
    print "Usage: %s property1 value1 property2 value2 [property3 value3]" %
(p\
rog_name)
    sys.exit(NUM_PARAM_ERR)

---
This way, I can get the error message and exit status from the program.

This does not seem particularly 'Pythonic' to me. I suppose I should be
using an exception class of some sort and raise these exceptions when they
occur.   Something perhaps like

---
class MyProgError(Exception): pass
class ImproperArgs(MyProgError): pass

if num_args != 6 and num_args != 4:
    raise ImproperArgs, "Usage: %s property1 value1 property2 value2
[property3 value3]" % (p\
rog_name)
---

Using this approach, is there a way to return an error status code [like
sys.exit()] as well as a message?

Are there other alternatives I should be considering? 

Any suggestions are appreciated.

-Brad