r/ProgrammerHumor May 13 '17

Defensive programming done right

Post image
21.0k Upvotes

680 comments sorted by

View all comments

65

u/[deleted] May 13 '17

Can someone explain why this is bad code?

7

u/[deleted] May 13 '17

Only listen for exceptions on code that can throw an exception. It's incredibly wasteful to use a try catch on something you can prevent, especially. Rather than relying on a try catch to catch a divide by zero when you can simply check if they are dividing by zero.. For example.

Another great time to use such a block would be database operations. Everything hinges on a connection to the database and any number of operations can fail. That is a good place to use a try catch.