Catching all exceptions *and* their args
Steve R. Hastings
steveha at animal.blarg.net
Tue Aug 21 23:04:44 EDT 2001
Hello. I'm a Python newbie who has searched a bunch of documentation
before posting this. If it's documented somewhere I missed, please point
me at the documentation.
I am trying to write a simple script using the getopt module. It turns out
that when you have an unexpected command-line flag, getopt raises an
exception.
Well, I said to myself, I don't care what the exception is; an unexpected
flag is grounds to exit the script. Easily done:
try
(options, arguments) = getopt.getopt(sys.argv[1:], "i")
except:
usage()
sys.exit(1)
And this works. If you pass "-i" as an option, all is well, but "-a" or
anything else prints the usage string and exits.
But I noticed that getopt was returning a nifty message explaining just
what the problem was. So I figured I would just catch all exceptions, grab
the error, and print it. Like so:
try
(options, arguments) = getopt.getopt(sys.argv[1:], "i")
except Exception, err:
print err
usage()
sys.exit(1)
It didn't work. I dug into the problem and found that getopt was raising a
string, rather than an exception object. (The default python on my system
turns out to be 1.5; if I explicitly use 2.0, the above code works
correctly, since in 2.0 getopt raises a subclass of Exception.)
So, my question: how can I catch all exceptions *and* grab the error
string? "except Exception, err:" only works with well-behaved functions
that only raise subclasses of Exception; I'd like code that works with
anything, including strings. I was planning to give away the script when
I'm done writing it, and in a perfect world the script would work under
either Python 1.5 or any newer version.
A truly general solution would allow catching all exceptions and grabbing
all arguments passed when the exception was raised. Is there such a
general solution in Python?
Thanks for your time.
--
Steve R. Hastings "Vita est"
steve at hastings.org http://www.blarg.net/~steveha
More information about the Python-list
mailing list