Total members 11894 |It is currently Mon Nov 25, 2024 9:58 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





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()
 




_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 1 post ] 

  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     -  
 usage of SQLite database from Python     -  



Topic Tags

Python Exceptions






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com