[Python-ideas] Use `isinstance` check during exception handling
Michael Selik
mike at selik.org
Sat Nov 7 17:28:49 EST 2015
Sorry about that. I also forgot to instantiate the class. Here's
functioning code...
class SqlSyntaxErrorHandler:
def __enter__(self):
return self
def __exit__(self, etyp, einstance, etraceback):
if (etyp is not None
and issubclass(etyp, sqlite3.OperationalError)
and 'syntax error' in str(einstance)):
print('Your SQL is bad')
return True
with SqlSyntaxErrorHandler():
cursor.execute(query)
On Sat, Nov 7, 2015 at 4:29 PM Terry Reedy <tjreedy at udel.edu> wrote:
> 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
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151107/7ee1010e/attachment.html>
More information about the Python-ideas
mailing list