Важно

  •  

Friday, July 24, 2009

Handling the exceptions in J2EE environment. Part II. (English)

You can find the first part here https://www.toalexsmail.com/2009/07/handling-exceptions-in-j2ee-environment.html

Scenario: When you check your business rule you use some API or some other module use you as API and something goes wrong.

This is highly debatable part. For example, you write public method that can be called from another module. Should you check that parameters are not null? What exception should you throw in this case? My point of view, that first, you should "defend" your code by making these kind of check and, second, it is SYSTEM Exception see point a) above. It is "unexpected exception". In many cases it point whether to incorrect use of your's API or to the bug in the code. If it is bug, it clearly has nothing to do with application, you should now about it as soon as possible in order to fix it. If it is incorrect use of API, it means that the problem is beyond responsible of your module, it is "environment" problem, even though the "environment" is just another part of your application.

Scenario: You write private method that receive some object from your own class. Should you check whether this object is not null? What exception should be thrown?

Many programmer says, "hey, you know how this method is called, why and where. Why should your private method bother about nulls? This is "never happen" check." My short answer is bug. You can have bug in your code and you want to have indication about it as soon as possible, because this will make tracing the root of the bug easier. So, I prefer to make this check. But I agree that in production environment it is redundant check. So, I use assertion mechanism introduced to JDK 1.4. For example, assert obj!=null. By default the assertion mechanism is switched off. There no even evaluation of this expression! So, in production the overhead is very low. In your debug\test environment your turn on assertion mechanism by supplying JVM parameter. You can turn on assertion mechanism globally to your application by supplying -ea. If assertion check fails java.lang.AssertionError is thrown (System Exception). In some places I throws deliberately AssertionError. For example, in the switch block that use java.lang.Enum, in the default case I throws AssertionError. I do it because most likely new value was added to enum and my code should be updated accordingly, so it is bug. Such thing can be happen in production, that why I want AssertionError to be thrown unconditionally in this case.

No comments:

Post a Comment