简体   繁体   中英

How to properly catch exceptions from another class?

Let's say we have this method in python module

A.py

class Database():
   #..../init, etc

   def bulk_insert_query(self, query, dataset: typing.Tuple) -> None:

        try:
            stmt = ibm_db.prepare(self._conn, query)
            ibm_db.execute_many(stmt, dataset)
            logging.info("Bulk insert executed successfully.")
        except Exception as e:
            logging.exception(f"Bulk insert failed: {e}")

I call this method in a different python module

B.py

import a.Database
db = a.Database()

try:
    db.bulk_insert_query(query = query, dataset = data_to_load)
except:
    sys.exit()

What I want to achieve is to the execution to stop when a.bulk_insert_query() fails for some reason (to the sys.exit() to run). I do not want to write the sys.exit() to the Database class, because it is used by other methods where I should not exit on error. So I am curious about the most pythonic way to raise the exception in the Database class, and catch that exception in other modules with try + except. I know I can use raise to pass exceptions, but I am not sure if it is makes sense to use it in a try - except block.

In an except block, a raise statement with no parameter will simply re-raise the caught exception so it can be caught and handled by the caller.

    except Exception as e:
        logging.exception(f"Bulk insert failed: {e}")
        raise

Re-raising is quite common in this kind of situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM