Home > Mobile >  How to properly catch exceptions from another class?
How to properly catch exceptions from another class?

Time:03-09

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.

CodePudding user response:

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.

  • Related