3
\$\begingroup\$

I have this function that I have written, that gets passed a row of data from a mysql function. The function then uses a try-except block to get some a list of values depending on a value within the row of data.

It then loops through this data and completes another try-except block within the first try-except block's else command.

In fact, a lot of my code is styled this way. Some blocks go on for so long, or other blocks start once one has finished. Is this good practice of writing code? Or should I refactor my code and move the second try-except block into another separate function?

def select_uploaded_series(row):    
        try:
            select_series_name = """SELECT track_ser_series 
            FROM track_series 
            WHERE track_ser_id = %s"""
            dbDets[1].execute(select_series_name,(row['track_id']),)
            series_names = dbDets[1].fetchall()
        except Exception as e:
            raise(e)
        else:

            names = []

            for series in series_names:
                try:
                    select_series_name_query = """SELECT title 
                    FROM series 
                    WHERE categoryId = %s"""
                    dbDets[1].execute(
                            select_series_name_query,
                            (series['track_ser_series']),)
                    track_series_names = dbDets[1].fetchall()
                except Exception as e:
                    raise(e)
                else:

                    for t_names in track_series_names:
                        names.append(t_names['title'])

            return(names)
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

If you're just going to re-raise the exception you caught, then there is no point in catching it in the first place. Instead of:

try:
    code block A
except Exception:
    raise
else:
    code block B

you can write:

code block A
code block B

and the behaviour is just the same.

\$\endgroup\$
1
  • \$\begingroup\$ Will do this with all my code. With regards to the other function should I implement that as well, or just use the format you have suggested? \$\endgroup\$
    – mp252
    Commented Jul 5, 2017 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.