In an effort to improve my coding, I was wondering if I should put try/except inside a function or keep it outside. The following examples display what I mean.
import pandas as pd
df = pd.read_csv("data.csv")
# Example 1
def do_something(df):
# Add some columns
# Split columns
return df
try:
df = do_something(df)
except Exception, e:
print e
# Example 2
def do_something(df):
try:
# Add some columns
# Split columns
except Exception, e:
print e
df = pd.DataFrame()
return df
df = do_something(df)
It might seem the same, but the first example is more clear on what happens while the second seems cleaner.
If the function can provide a sensible recovery from the exception and handle it within its scope of responsibilities and without any additional information, then you can catch the exception right there
Otherwise, it might be better left up to the caller to deal with it. And sometimes even in this case, the function might catch the exception and then immediately raise it again with a translation that makes sense to the caller
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With