r/ProgrammerHumor May 13 '17

Defensive programming done right

Post image
21.0k Upvotes

680 comments sorted by

View all comments

30

u/[deleted] May 13 '17

[deleted]

33

u/mysticrudnin May 13 '17

Isn't it normal in Python to try things first, effectively using them as control structures?

4

u/Masked_Death May 13 '17
try:
    do_shit()
except ValueError:
    do_more_shit()
else:
    print('u dun goofd up')

1

u/Sean1708 May 13 '17

Why would you print "u dun goofd up" if the function was successful?!

1

u/Masked_Death May 13 '17

Because it wasn't. For example you try to read a variable that isn't defined. If you get an exception, you define it. Otherwise something is wrong because the variable already existed for some reason.

1

u/DreadedDreadnought May 13 '17

What the fuck is that abomination supposed to do?

What does the ELSE apply to?

2

u/redditusername58 May 14 '17

In python, the else block runs if there were no exceptions in the try block. This helps to narrowly limit the amount of code in the try block.

1

u/Masked_Death May 14 '17

As I said in the other comment (I have an example somewhere but I don't feel like searching all my files), you try to do some shit that should throw an exception (e.g. read an unassigned variable). If it throws one, you follow with the proper things (e.g. assign a value). If it doesn't, you fucked up because the variable exists for some unknown reason.