[Tutor] Treating program exceptions
Sean 'Shaleh' Perry
shalehperry@home.com
Fri, 05 Oct 2001 08:02:46 -0700 (PDT)
> ---
> 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?
>
the item passes along with the exception can be any python object. So you
could do:
raise FooException, ('descriptive text', error_code)
> Are there other alternatives I should be considering?
>
Using an exception gives you the ability to handle similar errors in a similar
way or the same error in different ways.
try:
if num_args != 6 and num_args != 4:
raise ImproperArgs, (1, num_args)
if 'badoption' in arg_list: # this would not be a static string
raise ImproperArgs, (2, 'badoption')
...
catch ImproperArgs, info:
if info[0] == 1:
print "Either 4 or 6 options expected, %d seen" % info[1]
elsif info[0] == 2:
print "This option is obsolete, %s" % info[1]
print "Usage: blah blah"
sys.exit(info[0])
Now the usage string appears only once localized to where it will be displayed.
You could then wrap all of the initial arg checking in a function:
settings = parse_args(sys.argv)
try:
settings = parse_args()
catch ImproperArgs:
...