Explaining the Benefits of Re-Raising Exceptions in Python

The aim of this page📝is to explain the usefulness of re-raising exceptions with raise keyword via the 3 use cases.

Pavol Kutaj
2 min readSep 9, 2022

1. USECASE #1: BACKUP/ARCHIVE

  • Imagine the following code.
  • A little setup: You are responsible for maintaining a huge database of information for example, and any loss of data would be catastrophic!
  • Now, if you wanted to perform logging or cleanup that only occurs on failure, you could put that between the except: and the raise
  • → you’d do that work and then proceed as if the original exception was bubbling normally.
huge_dictionary = {'lots_of_important':['stuffs']}
try:
check_data(new_data) #make sure the data is in the correct format
huge_dictionary['lots_of_important'].append(new_data)
except:
data_writer.backup(huge_dictionary)
data_writer.close()
#and any other last-second changes
raise

— from https://stackoverflow.com/a/39144452/11082684

2. USECASE #2: EXCEPTION CHAINING

def multiplier(*args):
try:
i = iter(args)
result = next(i)
for the item in i:
result *= item
return result
except StopIteration as e:
raise TypeError("At least 1 argument is required") from e

>>> multiplier()
TypeError: Error: At least 1 argument required

3. USECASE #3: LOGGING / PASSWORD BLURRING

  • You can use query data in Redshift/another DB with Python and may want to log failures and replace credentials along the way
try:
redshift_host = "cluster01.redshift.foo.com"
redshift_db = "bar5"
redshift_port = 5348
redshift_user = "acme_108"
redshift_password = "password"
#... connect → execute → commit query against Redshift
except Exception as e:
logger.error(str(e).replace(redshift_password, "*"))
raise e

4. SOURCES

--

--

No responses yet