Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

exception handling try and catch in Python

Sat Jul 28, 2012 2:06 pm

Like other programming languages such as PHP, Java and C#, you can add exception handling to your code, imagine that you are starting a connection to database and want to handle the failure cases, in the following snippet an error is thrown because of inserting two database records with the same primary key value:

Code:

myConnection 
None

try:
    
myConnectionsdb.connect('/tmp/myDatabase.db')
    
    
myCursor myConnection.cursor()

    
myCursor.execute("INSERT INTO user(firstName,lastName) VALUES (?,?)", ('Adm','James') )

    
## try to insert a duplicate contact id
    
myCursor.execute("INSERT INTO user(user_id,firstName,lastName) VALUES (?,?,?)", (1,'Joe','Ibrahim') )

    
myConnection.commit()    
    
except sdb.Errore:
    
    
## rollback because of error 
    
if myConnection:
        
myConnection.rollback()
        
    print 
"Error %s:" e.args[0]
    
sys.exit(1)
    
finally:
    
    if 
myConnection:
        
myConnection.close()
 




Post a reply
  Related Posts  to : exception handling try and catch in Python
 Catch database connection exception     -  
 Exception handling     -  
 Exception Handling in a project     -  
 how to design a exception handling for a project     -  
 exceptions catch by a catch clause     -  
 hashing in python     -  
 how to use GeoIP with Python     -  
 Python Module for MySQL     -  
 Reading email in Python     -  
 How to read and write to CSV file from python     -  

Topic Tags

Python Exceptions