Why are error return codes evil? – level 100

Miller ran across some code today that used error codes for return values.  We exchanged some bad examples of misusing error codes (or just using them, period).

In languages without structured exception handling, we often used some sort of indicator to communicate when an error happened.  For instance, a DOS program (or batch file) has a return code retrievable using the ERRORLEVEL global variable.

With my platform of choice (.NET) supporting structured exception handling, using return codes for error reporting is quite far on the evil spectrum.  Consider this code:

   1:  public int DoSomething(){
   2:      //omitted implementation
   3:      return -1;
   4:  }

This method should be void.  It is using an integer to tell whether an error occurred or not.  If something went wrong, throw an exception:
   1:  public void DoSomething(){ 

   2:      throw new SomethingException();
   3:  }

Then there is no chance of the program continuing while being broken under the covers.  Some folks call this method “failing fast”.  If the program encounters a serios error that it can’t handle, fail fast because a program not operating according to plan can only cause harm.  That’s why so many people hate “On Error Resume Next” in VB.  Errors are simply ignored.  Some folks rigged up error handling in VB by using:

   1:  On Error Goto ErrHandler
   2:      ‘some code
   4:  ErrHandler:
   5:      ‘do some error reporting

The team had to be very disciplined to make this work.  One funny thing I came across was a statement like the following:

   1:  On Error Goto Hell
   2:      ‘some code
   4:  Hell:
   5:      ‘do some error reporting

Bottom Line:  Throw exceptions if something goes wrong.  Don’t set a “magic number” and expect to remember to check that later on.