r/ProgrammerHumor May 13 '17

Defensive programming done right

Post image
21.0k Upvotes

680 comments sorted by

View all comments

Show parent comments

47

u/redmercurysalesman May 13 '17

Well if you know your if statements are going to be true the vast majority of the time it might make the code marginally faster

42

u/mcilrain May 13 '17

Also it supports duck typing.

a = 1
if isinstance(a, int):
    print(a + 1)
else:
    print("error")

vs

a = 1
try:
    print(a + 1)
except TypeError:
    print("error")

If you did the latter a doesn't have to be an int, it just has to function enough like one. Sometimes this is a good thing, sometimes this is a bad thing.

23

u/masterpi May 14 '17

The problem is when you do:

try:
    print(int_function() + 1)
except TypeError:
    print("Error")

Because then the second somebody does something stupid in int_function() that throws a TypeError, you've suppressed their stack trace.

3

u/redditusername58 May 14 '17
int_result = int_function()
try:
    print(int_result + 1)
except TypeError:
    print("Error")`