except clause appears to be being skipped?

John Machin sjmachin at lexicon.net
Sat Mar 24 03:29:52 CET 2007


On Mar 24, 12:51 pm, AWasile... at gmail.com wrote:
[snip]
>         def pager(self,dex):
>         #Input page filename, Output pagetitle and the HTML output
>                 #Find out if the file requested actually exists
>                 try:
>                         j = dex + ".html"
>                         textfile = open("pages/" + j, "r")
>                 #If not 404' it
>                 except:
>                         self.err404(dex)
>
>                 #The first line in the .html files is the title, this reads that one
> line
>                 pagetitle = textfile.readline()
>
[snip]

>   File "/home2/awasilenko/webapps/cp/html.py", line 25, in pager
>     pagetitle = textfile.readline()
> UnboundLocalError: local variable 'textfile' referenced before
> assignment
>
> I know the except is being executed because I put a break in there for
> testing purposes and it did break, but as for why its not pulling up
> the 404 function and returning the error page, I have no idea.

It *is* "pulling up the 404 function", which *is* returning your error
page. However all your except clause does is "self.err404(dex)" -- you
ignore the return value, and fall out of the except clause with
textfile undefined, with the expected consequences.

I'm not at all familiar with cherrypy, but you probably need to do
either:
    errpage = self.err404(dex)
    dosomethingwith(errpage, dex)
    return
or simply:
    return "404 page title", self.err404(dex)
[Actually it would be better style if the err404 method returned a
tuple of (pagetitle, pagebody), then your except clause contains
only:
    return self.err404(dex)

The main point being to return instead of falling through the bottom
of the except clause. BTW, you should not use a bare except. Be a
little more specific, like except IOError:

Looking at the cherrypy docs would seem indicated. AFAIK there was a
v1 and a v2 with different naming conventions and there's now a v3 --
do ensure that you mention which version you are using if you need to
come back with more questions.

HTH,
John




More information about the Python-list mailing list