Re-raising a RuntimeError - good practice?

Victor Hooi victorhooi at gmail.com
Wed Oct 23 23:23:21 EDT 2013


Hi,

I have a Python class that represents a loading job.

Each job has a run_all() method that calls a number of other class methods.

I'm calling run_all() on a bunch of jobs.

Some of methods called by run_all() can raise exceptions (e.g. missing files, DB connection failures) which I'm catching and logging.

If any of the methods fails, I'd like to terminate running that job, and move onto the next job.

I'm currently re-raising a RuntimeError, so that I can break out the run_all() and move onto the next job. 

For example:

    def run_all(self):
        self.logger.debug('Running loading job for %s' % self.friendly_name)
        try:
            self.export_to_csv()
            self.gzip_csv_file()
            self.upload_to_foo()
            self.load_foo_to_bar()
        except RuntimeError as e:
            self.logger.error('Error running job %s' % self.friendly_name)
...
    def export_to_csv(self):
    ...
        try:
            with open(self.export_sql_file, 'r') as f:
                self.logger.debug('Attempting to read in SQL export statement from %s' % self.export_sql_file)
                self.export_sql_statement = f.read()
                self.logger.debug('Successfully read in SQL export statement')
        except Exception as e:
            self.logger.error('Error reading in %s - %s' % (self.export_sql_file, e), exc_info=True)
            raise RuntimeError

My question is - is the above Pythonic, or an acceptable practice?

Or is there another way I should be handling errors, and moving on from failures, and if so what is it please?

Cheers,
Victor



More information about the Python-list mailing list