Sorry, guys. Accidentally replied off-list.
--- Begin Message ---
Kirk Bailey wrote:
ok, try this:
Try:
You're still using an uppercase try. Python is case sensitive. Unless
you're doing some voodoo magic to make
Try be an alias for try, this won't work.
filename=sys.arv[1]
except Exception, e:
and you're still not catching the specific exception, so I don't see how
this is an improvement.
if filename='':
filename='foo' # define a default value
else:
if foo: # detect one likely error
foobarcode
else:
if bar: # detect another one
morefoobarcode
There is a keyword called 'elif' that does an else and an if at the same
time, so you don't have to have so much indentation.
Eg:
if foo == 'bar': do something
elif foo == 'barbar': do something else
#you don't need an else here unless you want one.
else: # final catchall for things you
# did not anticipate
But the point in only the specific exception you want to be caught being
caught is that you _want_ the exceptions you don't expect to still be
thrown,
not silenced and having this generic print statement.
It doesn't have a traceback, does it?
Print 'how the heck did you accomplish this?!? I QUIT~!
sys.exit(13)
As an example of this:
try:
f1 = sys.argv[1]
f2 = file("SomeFileThatMayNot.Exist","r")
except:
#since we have a generic except clause here, we don't know which item
raised the error.
#how do we figure out which one did?
#well, assuming we set f1 to "" before the try, we can do
if f1 != "": #therefore f2 must've raised the error (note the converse
is not true, if f1 == "" either f1 assignment raised the error or f1 was
assigned to an empty string)
print "Your file didn't exist!"
As you can see, there are a lot of complications that arise even from a
simple case.
Here's a much better way to do it (and the intended way to use the
'except' clause)
try:
f1 = sys.argv[1]
f2 = file("SomeFileThatMayNot.Exist","r")
except IndexError:
#the first statement failed
except IOError:
#the second statement failed
#an exception will be raised here if something we weren't expecting
created an error.
i has something vauely like this in the wiki on the slab right now,
except it was addressing the query string. other than that, same problem.
another idea is simply detect that there IS a argument;
if sys.argv[1];
This will still raise an IndexError if the length of sys.argv is less
than 2. That's the point of the try, so the IndexError exception can be
caught.
filename=sys.argv[1]
if condition:
do something
else:
do this instead
else:
filename="foo"
which avoids try altogether.
It terminates your program if the precondition isn't met, instead of
using a default value.
So it doesn't do the same thing as the try-except.
Somehow I kinda like this way more.
It's true you don't always need try-except blocks, but in this case it's
a good solution.
HTH,
-Luke
--- End Message ---
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor