Tuesday, December 9, 2014

Everything is Awesome... Well, with one Exception

Let's talk about my old buddy Murphy.  I've been developing software for...  is it really a quarter of a century now?  And his law is ironclad.  Things WILL go wrong.  Things will always be going wrong, I suppose, unless and until a perfect computer is combined with a perfect programmer.  I don't think I'll worry about my day job on that account just yet.

When a program encounters an error condition, it can give up in a panic or it can attempt to handle the situation.  If you try to open a picture in your favorite photo editor, and it turns out that despite the name of the file, it was actually a word processing document, you probably wouldn't want the software to crash.  If you deploy a new program at work and it chokes because you forgot to feed it all the command line parameters it needs, you probably want it to tell the operations staff what went wrong, rather than giving them the precious gift of a crash report with no supporting information.

Back in the old days, we had several methods of dealing with these sorts of errors.  Sometimes there would be a particular value that would only come back from a function is something had gone wrong.  Maybe you expected a result of 0 or higher, so if it came back as -1 you knew you had a problem:

    returnCode = deployLandingGear();
    if (returnCode == -1) {
      printf("ERROR:  deployLandingGear failed.  Please check operations manual.");
      return;
    }
    // deployLandingGear worked.  We can go ahead and attempt to land on Mars
    land();

Now maybe your code is not as mission critical as that, but the point remains that we wound up sticking our error handling there into the main body of our code.  At best this was annoying.  At worst we failed to account for possible errors, but of course not because the project manager was pressuring us to get code shipped.

Enter the Exception.

Exceptions are pretty much what they sound like.  Conditions that are outside the normal expectations you have for what your program ought to be doing.  Your 'deployLandngGear' method ought to work pretty much every time, unless there's something physically wrong with your lander.  Exceptions give us a method of keeping our code nice and clean, while giving us an effective 'hook' to deal with problems as they arise.

Exceptions require just a bit of coordination between calling and called methods.  Any method that wants to be able to notify callers of problems should specify this fact in its method signature.

So the header for the method 'deployLandingGear might be written like this:

    public void deployLandingGear() throws HardwareException {
      

'HardwareException' is an arbitrary name I just made up, but it has to refer to a valid class that extends Exception.  I could have had it just say 'throws Exception', actually, but it's generally better to have it be more specific than that.  This is particularly the case if, for instance, you wanted to have the constructor for the HardwareException accept parameters such, for instance, how far the gear had gone before the problem occurred, which subsystem failed, etc.

So HardwareException might be declared like this:

    public class HardwareException extends Exception {

And perhaps it has a constructor like this:

        public HardwareException(Subsystem failureIn, int percentComplete, boolean canContinueWithFailure) {

Of course, when it comes right down to it, I don't work for either NASA or SpaceX and I have no idea what their protocols might be in the event of such a failure.  Let's assume though, that the landing gear subsystem is consider deployed 'enough' if it's at least 85% deployed, and that it reports its position as an integer of said percent deployed.

Let's see what happens in one case of deployLandingGear failing.

    public void deployLandingGear() throws HardwareException {
      ...
      if (false == landingGear.isCycleComplete()) {
        throw new HardwareException(landingGear, landingGear.getPosition(), landingGear.getPosition() > 85);
      }

Here we have introduced the keyword 'throw', which fulfills the contract specified by the 'throws' clause in the method signature.  We call this 'throwing an exception' and it pretty much is exactly that.  When we throw an exception it's kind of like returning from the method, except that there is no return type specified, required, or allowed.  Also, the control flow in the calling program will be different.

If we try to write code to deploy the landing gear and fail to deal with the HardwareException, The Java compiler will complain.  Your code will simply not compile.  In order to call it you will have to use a special construct called a try/catch block.  This syntax is often confusing when you first encounter it, but basically, we are going to try to do something, and if it fails and throws an exception, we're going to catch that exception and deal with it.

It looks like this:

    try {
      deployLandingGear();
      land();
    }
    catch(HardwareException landingError) {
      System.out.println("Hardware failure.  Landing may not be possible.  Error was: " + landingError );
    }

OK, now we see that the actual code block for 'deployLandingGear' and 'land' is a bit cleaner than it was using the older style.  Of course, this would be much more the case if we had more than two lines of code in there.  We also see (and this is actually not a great way to write the code) that in the event of a failure, control passes down into the catch block, eliminating all chance that you might ignore the error due to a lack of coffee and try to land anyway.

In reality it's probably better to allow the HardwareException to pass further up to a higher level master control function,  You can do this automatically by not having the try/catch structure at this level and declaring that this method also throws such a beast.  You can also do it manually by simply calling 'throw landingError' inside the catch block.

You can have multiple 'catch' blocks one after the other, if you need to account for several different exception types.  You can have a 'catch' block catch a superclass of your exception and still catch it, so 'catch (Exception e)' would have worked fine here.  It gets involved, and there's no one right answer for all situations.  You must let your system requirements and sometimes your personal preferences guide you.

Finally (ha ha) there is the 'finally' block.  This is optional and can be placed after all catch blocks.  This is code that WILL be run, whether you hit an exception or not.  Once either the try block is finished, or any catch block is finished, your finally block will be run.  This can be handy if you absolutely must release some resources or post a message or something.

    try {
     doSomethingThatCouldFail();
     System.out.println("Succeeded.");
    }
    catch(Exception e) {
      System.out.println("This is why you fail: " + e);
    }
    finally {
      System.out.println("Do or do not, there is no try.");
    }

You can't ignore exception handling, but it's possible to do it poorly.  The better you deal with things that go wrong, though, the more robust and resilient your software will be.  If you can change some setting and make another attempt, so much the better.