user2164689
user2164689

Reputation: 377

Try exception handling

I am trying to make an insert of update statement in Python 2.7. I am using Try and Except, but figured that sometimes the except might fail as well. Is there a way to capture this error?

What I mean is the following:

try:
    execute insert statement [example]
except: 
    execute update statement [example]
    WHAT IF THIS FAILS? (This is my question)

Seems that this is something that is not really documented. By the way, using Postgres and could not find a proper UPSERT and this was suggested somewhere on StackO.

Upvotes: 0

Views: 831

Answers (4)

Bruno
Bruno

Reputation: 122719

In general, have another try block within your except block:

try:
    Attempt something here.
except:
    try:
        Attempt something else here.
    except:
        Handle the problem here.

However, this is probably not going to solve the problem in your example:

try:
    execute insert statement [example]
except: 
    execute update statement [example]

Failing to insert first will certainly invalidate your transaction (assuming you're using transactions): in this case, the update statement will fail too. (If you're not using transactions, both statements could fail too, anyway.)

You could instead instead have a look at other strategies for UPDATE/INSERT in PostgreSQL, for example this question.


Here is a full example illustrating the problem with this suggested try/except approach to upsert:

import psycopg2

conn = psycopg2.connect(database='test_so27843654')
cursor = conn.cursor()

cursor.execute("DROP TABLE IF EXISTS test_table")
cursor.execute(""" CREATE TABLE test_table (
                        id INTEGER PRIMARY KEY,
                        val TEXT
                   ) """)
cursor.execute("INSERT INTO test_table (id, val) VALUES (1, 'Test 1')")

try:
    cursor.execute("""
        INSERT INTO test_table (id, val) VALUES (1, 'Other Test 1')
    """)
    print "Inserted..."
except:
    try:
        cursor.execute("""
            UPDATE test_table SET val='Other Test 1' WHERE id=1
        """)
        print "Updated..."
    except:
        raise

conn.commit()

This will always fail with: psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34166

You can nest try-except clauses:

try:
    execute insert statement [example]
except: 
    try:
        execute update statement [example]
    except:
        handle the errors

Note: You should especify the exception type in the except clause:

except InsertException: # or the one that fits better

Edit: If the update will fail if the insert fails, then it doesn't make sense to put the update statement in the first except.

Upvotes: 3

Eithos
Eithos

Reputation: 2491

If that happens, all you really have to do is this:

try:
    execute insert statement [example]
except: 

    try:
        execute update statement [example]
    except: 

It works as you'd expect.

Upvotes: 0

fredtantini
fredtantini

Reputation: 16566

You can nest try/except:

>>> try:
...   1/0
... except:
...   print "in except"
...   try:
...     "1"+[1]
...   except:
...     print "second one"
...
in except
second one

In your case:

try:
    execute insert statement [example]
except: 
    #insert failed
    try:
        execute update statement [example]
    except:
        #update failed

Upvotes: -1

Related Questions