Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Catch exceptions

Thread Tools

Catch exceptions

Cruella DeVille
Posts: n/a
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):
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

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

Reply With Quote
Posts: n/a
Without seeing more of your code, I'm not sure what you are doing
wrong. This works:
vvvvvvvv vvvvvvvvvvvvvv
def xopen(path):
return open(path)
except IOError, e:
print 'Error:', e.args[1]

$ python
Error: No such file or directory

Could you give us the traceback?

Reply With Quote
Cruella DeVille
Posts: n/a
I put the try catch in my main-method, and it worked to some extent
(except from when I try to read from a file with no content)

Any idea how to solve that?
And is it a good place to have a try-except in main instead of in the
class methods?

My code is at

Reply With Quote
Jonathan Gardner
Posts: n/a
(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.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
catch doesn't catch a thrown exception Marteno Rodia Java 5 08-05-2009 03:30 AM
How do I catch unhandled exceptions Alan Silver ASP .Net 5 03-23-2006 08:51 PM
catch(...) doesn't catch everything Adam C++ 9 02-02-2006 05:02 PM
why catch (...) can not catch such exception John Black C++ 8 08-20-2004 02:34 PM
How to catch multiple Exceptions Chris Berg Java 8 01-19-2004 10:11 PM