Marco Dinatsoli
Marco Dinatsoli

Reputation: 10580

python mysql can't catch the exception

This is my code

self.conn = MySQLdb.connect(user='SomeUser', passwd='MySecruitPassword', db='scrapy', host='MySecruitHost', charset="utf8", use_unicode=True)
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute(""" My secruit query """)))
            self.conn.commit()
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            errorMessage = "Error on {0} : {1}".format(e.args[0], e.args[1])
            self.sendEmail(errorMessage, "MySQL Exception 1")
        except Exception as ee:
            errorMessage2 = "Error on {0}".format(str(ee))
            print errorMessage2
            self.sendEmail(errorMessage2, "MySQL Exception 2")

I already know the exception, why it is happening, and how to solve it. However, I am trying to catch it.

as you see, i did two level of try and catch, and yet, my custom error message is not appearing. I just got exception states that there is an exception when trying to connect to my mysql in this line of code MySQLdb.connect(... , but i don't get my custom error message.

may you help please?

i am using python 2.7 on windows 7 and 64 bit

Upvotes: 0

Views: 332

Answers (1)

Yoel
Yoel

Reputation: 9614

Since the exception is raised by the MySQLdb.connect() method, you should include it in the try .. except code block.

Upvotes: 2

Related Questions