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.

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

I'd like to consider handling exception in a broader way.
There is 2 type of exceptions - System Exception and Application Exception. System Exception are usually fatal one and they related to the environment where the program run. For example, DB goes down or OutOfMemoryError occurred. Basically it means, that something goes wrong not in the application code but beyond the scope of application. Application Exception are Exceptions that generated by the application. Your application is totally responsible for handling it. One Example can be user put letter in the number field, or some business rule is violated.

Before I will continue I want to make one quick note. All Errors are System Exception (Errors are not intended to be caught by the application in any place). Mostly all RuntimeException are System Exception. Some API defines their "Application Exception" as RuntimeException, though. And there are some scenarios where your application treats RuntimeException as "Application Exception" in order to recover. All Exceptions that you defines in your own application are "Application Exception". All not yours Exception should be "Application Exception" also, but this is not always the case. Generally in the latest case it points out on bad design decision.

System Exception is treated in the following ways:
- let propagate it up to the stack to eventually crash the JVM. This is generally the best strategy with Errors. If OutOfMemoryError occur you can nothing to do with it;
- let propagate it to some high level, log it, and forward the user to the error page. This is generally the best strategy with so-called "unexpected exceptions";
- ignore the exception, wait timeout amount of time and retry or make other recovery strategy. This is rarely used strategy. This means that you work with low level API, if you have to do such things.


Application Exception can be roughly subdivided into two categories:
a) Application Exception that indicates illegal input of the user;
b) Application Exception that indicates violations of the business rule by the user;

a) Application Exception that indicates illegal input of the user.
- the best strategy will be to check all input and to show to the user message with all mistakes he make.
- alternative strategy will be to stop input checking on the first illegal input encounter. Obviously, the former strategy is better, but sometimes you have complex relationship within your input and you don't want to continue to make input validation if something basically goes wrong.

b) Application Exception that indicates violations of the business rule by the user.
Scenario: You make some basic input validation and you start to proceed the user request. Suddenly you discovered that some basic business rule is violated. For example, Customer doesn't exist in the DB.
- the best strategy will be to throw some "Business Exception" to the UI layer that indicates the problem. On practice it doesn't enough because UI has no idea what message should be displayed to the user. Theoretically, UI layer has investigate each exception, each exception has to have enough information, say subscriberId, in order to generate informative message. On practice, message that will be shown to the user is generated in the place where Application Exception occurred and is put on the Exception object itself or in some "global message container".

To be continued.

Два израильтянина госпитализированы в тяжелом состоянии с диагнозом свиной грипп


В Израиле впервые зафиксированы два случая острой формы свиного гриппа у людей, не входящих в группу риска. 13-летняя девочка из Ашдода была госпитализирована в детском отделении больницы "Тель а-Шомер" в тяжелом состоянии. По словам врачей, у нее обнаружено острое воспаление легких, спровоцированное вирусом гриппа H1N1.

Кроме того, в больнице "Вольфсон" в тяжелом состоянии госпитализирован 50-летний житель центра страны, также страдающий от воспаления легких, спровоцированного свиным гриппом.

До сих пор в Израиле были зафиксированы четыре случая тяжелой формы заболевания, однако все пациенты входили в группу риска. 25-летняя женщина была доставлена в больницу на 9-м месяце беременности, и еще три человека страдали хроническими заболеваниями. Двое из них до сих пор находятся в тяжелом состоянии и подключены к аппаратам искусственного дыхания.

Между тем, министерство здравоохранения приняло решение прекратить проводить лабораторный анализ в каждом случае подозрения на свиной грипп. Специальный препарат Tamiflu будут получать только больные, входящие в группу риска и те, у кого заболевание развилось в острой форме.

http://txt.newsru.co.il/arch/israel/23jul2009/gripp303.html
За развитием событий следите здесь свиной грипп

Израиль готов отказаться от американской военной помощи


В службах безопасности Израиля просчитывают варианты функционирования силовых структур без американских ассигнований на оборонные нужды страны. Делается это на тот случай, если США наложат экономические санкции на Израиль из-за отказа свернуть строительство в поселениях и Иерусалиме.

...В свою очередь руководители силовых структур Израиля провели негласные слушания, в ходе которых пытались получить ответ на главный вопрос: не пострадает ли оборона страны в отсутствии ежегодной 2,8-миллиардной помощи из США. (Обычно на эти деньги приобретается оружие в самих США.)

По ходу дебатов генералы пришли к выводу, что без американской помощи функционировать система безопасности сможет, хотя для этого и потребуется привлечь дополнительные резервы.

"Прекращение военной помощи будет чувствительным, но не системным ударом", - прокомментировал ситуацию корреспонденту газеты "Маарив" источник в минобороны. По мнению того же источника, США пострадают от прекращения военного сотрудничества с Израилем "в неменьшей степени".

При необходимости, считают военные, Израиль сможет приобретать технику (например, самолеты) во Франции, причем за меньшие деньги. Ранее США блокировали подобные сделки, чтобы не допустить оттока капитала от своей оборонки.

В военных кругах полагают, что партнерские отношения могут быть заключены с Россией, Индией и Китаем. В этой связи "Маарив" напоминает, что опыт сотрудничества в оборонной сфере с Россией уже имеется и, если бы не противодействие США, то масштабы его (сотрудничества) могли бы быть гораздо более широкими.

Поэтому, полагают военные, экономические санкции со стороны США не будут эффективными. Опасения же, что санкции примут глобальный характер и будут поддержаны прочими странами, источники "Маарива" считают несостоятельными, так как "тут завязано слишком много интересов" со стороны различных государств.

http://cursorinfo.co.il/news/novosti/2009/07/23/us_voina/

Умерла Бренда Джойс, сыгравшая самую сексуальную Джейн в саге о Тарзане



В США на 93-м году жизни скончалась знаменитая актриса Бренда Джойс. Свою последнюю роль в кино она сыграла в 1949 году, но весь мир помнит ее и сегодня по роли красавицы Джейн в фильмах о Тарзане.

http://www.newsru.co.il/arch/rest/23jul2009/brenda_301.html
http://cursorinfo.co.il/news/culture/2009/07/23/brenda/