[Tutor] Treating program exceptions

Joerg Woelke lumbricus@gmx.net
Fri, 5 Oct 2001 19:58:14 +0200


On Fri, Oct 05, 2001 at 09:45:51AM -0400, Reisfeld, Brad             CAR wrote:
> 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) 
> 

import errno
print errno.errorcode

> arg_list = sys.argv

IMHO there is no need for that.

> prog_name = os.path.basename(arg_list.pop(0)) 

why not just sys.argv[0]

> 
> if num_args != 6 and num_args != 4:

len(sys.argv)
man getopt ;-)

>     print "Error: Improper number of arguments."
>     print "Usage: %s property1 value1 property2 value2 [property3 value3]" %
> (p\
> rog_name)
>     sys.exit(NUM_PARAM_ERR)

$ cat ret.py
#!/usr/bin/env python

import errno
import sys
import os

x="3.2"
y="murks"

def main():
        try:
                float(x)
                float(y)
                ret=x/y
        except ValueError:
                print os.strerror(errno.EINVAL)
                sys.exit(errno.EINVAL)
        else:
                print "%.3f / %.3f = %.3f" %(x,y,ret)

if __name__=="__main__":
        main()
$ ./ret.py
Das Argument ist ungültig
$ echo $?
22
$

> 
> Any suggestions are appreciated.
> 
> -Brad
> 

HTH,HAND
and Greetings J"o!

-- 
A writer is congenitally unable to tell the truth and that is why we call
what he writes fiction.
		-- William Faulkner