Exceptions: use them

Exceptions have been around for a long time. There’s no reason not to use them.

I don’t want to ever see code such as this ever again.

if ( ! $user) return false;

We all know what happens with such code:

  • Nobody checks the return value
  • Especially if half the code is written using exceptions, and half using return values, then definitely nobody will check the return code
  • It breaks the linguistics of the language. A function called “getUser” should return a User, but a function called “deleteFile”: why does it return “true” or “false”?
  • Where are the log statements, stating why this function returned false? What if the function has multiple places to return false? Then (perhaps) the calling function can print the log “function deleteFile returned false” but that doesn’t tell you which of the multiple places failed.
  • What if you want to programmatically check the return result of the function? If all the errors return the same value, there’s no way you can programmatically respond to each error differently (as some might be permenant errors such as the file doesn’t exist, some might only be temporary errors such as network currently unavailable.)

Every language in use today, at least in the projects I work on, has ways of handling exceptions.

  • PHP5 has exceptions.
  • Java has exceptions.
  • C++ has exceptions.
  • Perl has “eval” and “die” which are like exceptions.
  • Javascript has exceptions.

One needs to simply be assertive, realize that exceptions are much better, and insist on using them.