0

Trying to handle an exception raised by SQLAlchemy in my Python code I wrote the following:

import sqlalchemy.exc as sqlalchemy_exc

try:
    ...
    db.session.commit()
except sqlalchemy_exc.SQLAlchemyError:
    raise

that isn't a good idea as handled exception is too wide. How to get the particular exception type was raised?

UPDATE

@Dan presented in his answer a reference where several solutions can be found. Two of them are following:

import sqlalchemy.exc as sqlalchemy_exc
    ...
    try:
        ...
    except:
        import sys
        print(sys.exc_info())

and

import sqlalchemy.exc as sqlalchemy_exc
    ...
    try:
        ...
    except:
        import logging
        logging.exception('')
Andriy
  • 1,270
  • 3
  • 17
  • 35

1 Answers1

1

You can try to print it first to see which exception it is: How to log python exception?

Then you can modify your code to catch the more specific ones you're interested in handling differently, eventually leaving the printing stuff in the catch-all case at the end - allowing you to identify other specific exceptions you might want to add to your code down the road.

try:
    ...
except sqlalchemy_exc.ArgumentError:  # specific exception
    pass  # do something else here if you want
except sqlalchemy_exc.SQLAlchemyError:  # catch-all
    # keep the printing stuff if you want
    raise
Community
  • 1
  • 1
Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97