Hello ,

I have had a little surprise and maybe because I haven't read the manual well enough or can't understand all the underlying details.

Imagine a small class and another file's main using an instance of that class. If I try to modify (not define !) an INEXISTANT attribute of the class in a try..except, i will get the print outs in except because the attribute doesn't exists, but how do i recover the message which indicates why the statement jumped to the except part?

class incomplete:
    def __init__(self):
        self.first  = 1
        self.second = 2
        
    
    
i = incomplete()
try:
    print i.first
    print i.second
    i.third += 3
    print i.third + i.first
except:
    print 'in exception'

Prints out
1
2
in exception

Any ideas please?

Thanks,

T

There is no problem with python. What it does is that it prints the first two, tries to add to the i.third and finds it cant. Then it goes to the except: statement and that prints out, in exception

Oh and to get the reason i think it is;

except Exception,e:
    print e

Thanks, I had seen that once some years ago but haven't been using it a lot since...

I can't resist giving you a sexy solution

import sys
import webbrowser
import cgitb

def output_exc():

    f = open("exception.html", "w")
    f.write(cgitb.html(sys.exc_info()))
    f.close()
    webbrowser.get("firefox").open("exception.html")
    # or webbrowser.open("exception.html") if you don't use firefox


class incomplete:
    def __init__(self):
        self.first  = 1
        self.second = 2
        
    
    
i = incomplete()
try:
    print i.first
    print i.second
    i.third += 3
    print i.third + i.first
except Exception:
    output_exc()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.