Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put try/except?

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.

like image 739
IordanouGiannis Avatar asked Dec 19 '22 01:12

IordanouGiannis


1 Answers

Possibility of internal handling

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

Raise or translate to caller

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

like image 197
bakkal Avatar answered Dec 26 '22 10:12

bakkal