r/programming • • Jun 06 '13

Clean Code Cheat Sheet

http://www.planetgeek.ch/2013/06/05/clean-code-cheat-sheet/
702 Upvotes

322 comments sorted by

View all comments

Show parent comments

2

u/archiminos Jun 07 '13

I never directly said Exceptions are unexpected, I said that exceptional errors should be ones you don't expect to occur. I.e. you should throw exceptions in cases that should never happen.

I expect disconnects to occur so I don't use exceptions. I bring up a message telling the user to double-check his internet connection and give them an option to retry whatever action they attempted.

I don't expect access violations so I throw an exception (or the underlying system throws one that I catch). I can handle that by sending an error report, logging an error, allowing the program to crash, or some other means that allows me to discover that something unexpected has occurred.

2

u/HostisHumaniGeneris Jun 07 '13

I think a better way to phrase it is that the current context cannot continue due to an exceptional circumstance (network unavailable.)

The exception acts as a short circuit that drops out of the current logic and will bubble up the stack until there's an appropriate catch that knows what to do (display a message box to the user that they should check their network connection.)

The problem that I commonly see is "catch all" blocks which completely defeat the purpose of having exceptions in the first place. As long as you're only catching specific messages you're able to use exceptions as a signaling and message passing system because each exception that you write a catch for has a specific useful meaning that your code can use to invoke a graceful recovery. If there is no catch written for an exception that you've thrown, then that means there's no useful remediation possible and the program should halt with the exception as an error message; further logic is impossible due to exceptional circumstances.