Java best practices for parameter checks and exceptions

Maybe you too had to use a Java library where the classes and methods you used had much exception throwing in their signatures (like, for example, when method parameter checks failed). And as a good Java programmer, you did not just pass on the exceptions, but did some meaningful handling of them. But then you realized that all this try {...} catch {...} finally {...} stuff made your code cumbersome to read and navigate, and needlessly lengthy …

So if you had to develop a Java library, how to do better? Here is my proposal:

The classes which are intended to be actually used by the the user of a library (or web application backend) should not throw many exceptions. Instead they should mainly log those which they receive from lower level classes of that library or backend. These error messages in the log will help the developer to tune the code, so that in real world production usage, the application will not run into errors (which means nearly not, of course). Such a low-error environment can be created wherever one can create a “closed environment”, which means, one where an initial valid state can only lead to more valid states. What can disturb such a clean “closed environment” is of course, user input. Therefore, input has to be checked thoroughly before passing it to the library or backend.

Note that, in this proposal, it is not the task of the library or backend to check any input. It simply specifies which input it expects, and then relies on that. Because if it had to do checks, it would also have to throw many different exceptions. But this way, it will only have to throw exceptions for critical errors, that is, those where something that should have worked did not.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.