Exceptional Exceptions

Leena
Continuous Delivery
2 min readNov 22, 2017

Exception handling is the process of responding to the occurrence, during computation, of exceptions — anomalous or exceptional conditions requiring special processing — often changing the normal flow of program execution.

Above is the definition of exceptions as per Wikipedia. Exception handling is for handling exceptional cases, handling unexpected events during the execution of a program. Few examples are:

  • Network connectivity issues
  • Issues while reading or writing to a file

When to use them

One of the problems with exceptions is knowing when to use them. We believe that exceptions should rarely be used as part of a program’s normal flow; exceptions should be reserved for unexpected events. Assume that an uncaught exception will terminate your program and ask yourself, “Will this code still run if I remove all the exception handlers?” If the answer is “no,” then maybe exceptions are being used in nonexceptional circumstances.

The Pragmatic Programmer

Let's look at an example:

The exception ActiveRecord::RecordInvalid can happen when the user enters invalid data. A user entering invalid data is not an exceptional case, and that is the reason why we’ve validations. In most of the cases, checking for invalid data is better than considering invalid data as an exceptional case.

Rails, the framework I used for the above code snippet, has the method object.valid? to check whether the object is valid to save. Another way is to use object.save (without the !) which returns false if invalid.

Eating Exceptions

The above is very common too, not doing anything when an exception occurs. If exceptions and exceptional, they will need attention and should be handled with respect.

When using editors such as IntelliJ or Eclipse for Java, its auto-complete feature generates empty blocks for exceptions. I try to avoid auto-generated code or change the template to avoid empty blocks.

Isolate Exception handling

An exception represents an immediate, nonlocal transfer of control — it’s a kind of cascading goto. Programs that use exceptions as part of their normal processing suffer from all the readability and maintainability problems of classic spaghetti code.

The Pragmatic Programmer

The above code is very difficult to read because of too many exception blocks. Try to avoid them using better design principles such as abstraction.

Refer to a few other examples as recommended by Avdi Grim in his talk — Exceptional Ruby

Use error monitoring tools to report errors whenever it happens. These help us to design our systems for failure.

--

--

Leena
Continuous Delivery

Co-founder/CTO @ PracticeNow, Bangalore, India. A strong believer of lean principles, an evangelist and practitioner of Continuous delivery