Re-raising a RuntimeError - good practice?

Andrew Berg robotsondrugs at gmail.com
Thu Oct 24 00:42:53 EDT 2013


On 2013.10.23 22:23, Victor Hooi wrote:
> 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
You're not re-raising a RuntimeError. You're swallowing all exceptions and then raising a RuntimeError. Re-raise the original exception in
export_to_csv() and then handle it higher up. As Steven suggested, it is a good idea to handle exceptions in as few places as possible (and
as specifically as possible). Also, loggers have an exception method, which can be very helpful in debugging when unexpected things happen,
especially when you need to catch a wide range of exceptions.

-- 
CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 10.0



More information about the Python-list mailing list