Tag Archives: exceptions

Error Handling & Exceptions

What makes a good method?

“The specification should be coherent: it shouldn’t have lots of different cases. Long argument lists, deeply nested if/for/while/switch statements and boolean flags are a sign of trouble.” – MIT 6.005 2011 lecture 3.

A method should just do one thing. Handling an error is one thing. So, how do we handle errors?

The Java experts and fans preach the use of checked exceptions on some situations. But I agree with Bob Martin (Clean Code book) when he says that checked exceptions are an Open/Closed Principle violation. They can sometimes be useful when writing a really critical library (you must catch them), but in general application development the dependency costs outweigh the benefits.

Another way to handle some errors is returning special values such as null or constant errors codes. But I’ve experienced the suffering of writing and reading ugly code with nested if’s or while’s just asking if object.method() != null/-1/Class.ERROR_CODE. To avoid that kind of nasty code, don’t return null, don’t pass null and don’t use error codes of any type. Use (unchecked) exceptions or return a SPECIAL CASE object instead.

On the other hand we have seen that exception could confuse the simple communicated main flow when catching them. Then, let it be your last resource: express control flaws with sequence, messages, iteration and conditionals (in that order) wherever possible.

When you could do something with a loop or if the server class has a boolean method that verifies for you the possibility of doing something, don’t try and catch.

3 Comments

Filed under Software Construction