1

I'd like to catch any type of error in Python3.

I'm trying something like that:

try:
   fields = line.split(' ')
   ...
   <PostgreSQL query execution>

except psycopg2.Error:
                    conn.rollback()
                    QUERY = "UPDATE table SET error='sql'"
                    cur = conn.cursor()
                    cur.execute(QUERY)
                    conn.commit()
                    cur.close()
                    continue
except:
                    conn.rollback()
                    e="generic"
                    QUERY = "UPDATE table SET error='generic'"
                    cur = conn.cursor()
                    cur.execute(QUERY)
                    conn.commit()
                    cur.close()
                    continue
                    

But I noted that, for example, an IndexError is not caught and the script fails.

What's wrong?

Thanks!

Fab
  • 1,145
  • 7
  • 20
  • 40
  • Does this answer your question? [About catching ANY exception](https://stackoverflow.com/questions/4990718/about-catching-any-exception) – Ruli Oct 08 '20 at 08:24

1 Answers1

1

This happens when a new exception occurs in the except block.

For example:

try:
    print('foo')
    raise ValueError
except:
    print('noes!')
    print(1/0)

Will exit with divide by zero exception.

In order to see if it is so, we need more of actual code from you, particularly both of the except blocks.

If you want to make sure you catch "any" exception, make sure your except blocks are unexceptional.

Gnudiff
  • 4,297
  • 1
  • 24
  • 25
  • Actually the script fails with "IndexError" exception. I've just edited the question adding the two except blocks. – Fab Oct 08 '20 at 16:15
  • As you suggested, there was an error in the sql statement. – Fab Oct 08 '20 at 16:52
  • @Fab Glad I could help. Please note that catching an SQL error and trying more SQL in except block is by definition error prone (even if there wasn't an error in query). What if the initial exception happened because you lost connection to the server? The rule of thumb in except blocks is to use as little code dependant on external environment as possible. Or something that fails gracefully such as syslog message. – Gnudiff Oct 08 '20 at 17:15