Catch exceptions

C

Cruella DeVille

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"?
 
C

Crutcher

Without seeing more of your code, I'm not sure what you are doing
wrong. This works:
vvvvvvvv ex.py vvvvvvvvvvvvvv
def xopen(path):
try:
return open(path)
except IOError, e:
print 'Error:', e.args[1]

xopen('xyzzy')
^^^^^^^^^^^^^^^^^^^^^^^^^^
$ python ex.py
Error: No such file or directory

Could you give us the traceback?
 
J

Jonathan Gardner

(A) You'll have to be more specific about your problem if you want us
to help. Under which circumstances did it work or not? What exactly is
the problem?

(B) Where you put your error-handling is up to you. It depends on what
the function does and how it is to respond. Do you want the function to
throw an exception if the file is not found, or do you want it to do
something else? Think about the interface of the functions (which is
the sum of the parameters, response, possible exceptions, and expected
behavior) and it should be clear where to put the exception handling.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top