[Python-ideas] Use `isinstance` check during exception handling

Terry Reedy tjreedy at udel.edu
Sat Nov 7 16:29:04 EST 2015


On 11/7/2015 2:18 PM, Michael Selik wrote:

> The current code pattern for a single try/except is to catch the general
> exception and have an if-condition in the except block.That's a frequent
> and readable practice.
>
>      try:
>          cursor.execute(query)
>      except sqlite3.OperationalError as str(e):
>          if 'syntax error' in str(e):
>              print('Your SQL is bad')
>
> If that code or similar code appears many times, a good way to refactor
> with the current features of Python is to use a context manager.
>
>      class SqlSyntaxErrorHandler:
>          def __enter__(self):
>              return self
>          def __exit__(self, etyp, einstance, etraceback):
>              if (issubclass(etyp, sqlite3.OperationalError)
>                  and 'syntax error' in str(einstance)):
>                      print('Your SQL is bad')

I like this example of how to use the error handling ability of __exit__ 
to set up an 'error handling context.  This is much clearer than the 
examples in the pep.  However, I checked and
issubclass(None, whatever) does not work.  True should be returned when 
the exception is handled.

     def __exit__(self, etyp, einstance, etraceback):
         if (etyp and issubclass(etyp, sqlite3.OperationalError)
                  and 'syntax error' in str(einstance)):
             print('Your SQL is bad')
             return True

>      with SqlSyntaxErrorHandler:
>          cursor.execute(first_query)
>
>      with SqlSyntaxErrorHandler:
>          cursor.execute(second_query)

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list