Thursday 13 October 2011

Exceptions (again)

The argument that keeps on giving :)
This is the fairest assessment that I think I've ever made of exception (specific to java, possibly).

Exceptions are a very good way of having more than one return type on call. Originally they were invented so that constructors could inform the caller of something rather than having to have a special "error" type of every class.
Handling exceptions early isn't always the best idea, code where an exception occurs may not be best suited to remedy it as the lowest level tends to be a generic handler of something.
Take for example the File API, if a file can't be found it is highly unlikely that the File object should be made to handle every failure adequately. Maybe it should simply return a null, but how then do we know the file couldn't be found rather than it couldn't be read? These 2 scenarios should be handled in very different ways (1) file not found: get the user to pick another (2) read error: try again X times then fail. Scenario 1 requires user interaction so bubble the exception up through the code so the user can pick another file.
There is also an argument against interpreting an exception at a lower level and sending specific "error" style replies up the chain.
  1. Multiple levels in the call stack will have to handle error return states.
  2. The returned objects would each have to have an error version created i.e.
    public A getA()
        public B doB()
            public C getC()
    
    each return type A, B, C would have to have an error version created, plus each call would have to handle this.
  3. There is already an adequate mechanism to repeatedly send exceptional responses up the stack regardless of method return type.
  4. Sometimes it is impractical to escape from a normal flow and return a meaningful error, the use of try catch blocks greatly simplifies this.

Also
Also the idea that exceptions are errors is flawed, exceptions are an
exceptional flow, the clearest use of this fact I think is the Thread
usage of InterruptedException. When things are running concurrently (even
pseudo concurrently) a message should be sent at any point during the flow
and the way to handle this is with exceptions.

The problem is that with legacy old shit (and I mean it is shit) does
the biggest sin of all which is to catch ALL general exceptions and simply
throw it without adding a cause to it. No attempt is made to handle the
exception where it is relevant which means the final resting place of a
thrown exception is the client which is why some people believe that the client
shouldn't handle them because 9 times in 10 the client is the wrong place
to handle them.

No comments:

Post a Comment

 
Stack Overflow profile for Richard Johnson at Stack Overflow, Q&A for professional and enthusiast programmers