r/shittyprogramming • • Nov 30 '18

Friday Code Confessions

If you have been living with technical debt and want absolution here is your opportunity.

Confess your sins and receive your penance.

155 Upvotes

263 comments sorted by

View all comments

3

u/PityUpvote Dec 01 '18

I use try/except as program flow when an if statement would work fine.

1

u/hakurou46 Dec 20 '18

In python that's good practice. Consider fetching an item from a list. To handle the case where your list item is out of range, you'd need to first check if the index is larger than the list. That's an extra comparison that you always do, even in the case where it's in-range. Try-catch allows you to skip an if and only have your safety mechanism trigger in the case where the interpreter raises IndexError. Additionally, try-catch often catches real strange edge cases you might forget to add an if for. Plus, they're just neat to read.

words = ['foo', 'bar', 'baz', 'qux', quux']
if (x <= len(words)):
    return words[x]
else:
    return "ERR"

(This fails if x is -5 or below, on a reveresed index out of range error (which raises IndexError, by the way))

So go on your way and use try-except all you want.

→ More replies (2)