Catch exceptions

Cruella DeVille siv.hansen at gmail.com
Mon Feb 27 18:38:05 EST 2006


In my application of bookmarks I get a filename as a parameter in one
of my methods. I want to catch the "FileNotFoundException" if the user
types an invalid filename. My code (that doesn't do what I want it to
do - namely print a nicely formatted error message, and no stack trace)

def openFile(self):
        try:
            return open(self.fileName, self.mode)
        except IOError:
            print("%s" %("The file was not found"))

But this one never occurs even if I write the name of a non-existing
file.

I also assign a variable, filePointer to a filename (the result of
openFile(self)), with a AttributeError
 if self.filePointer is None:
           raise AttributeError, "Assignment failed"

But I still get this stack trace (or trackback?)

How do I implement a try- except? Is it in my method where i open the
file or when I try to open the file in my "main-method"?




More information about the Python-list mailing list