вторник, 13 октября 2009 г.

Exceptions handling and reflection

There are Java reflection developed in such way that you cannot handle any exception which was throwed in the object method you call by invoke. It's not good, but you can handle it by using next solutions:
1. Present exceptions in target object not as exception in full-mean but as data-objects which can be accessed by external interfaces, for example:



class X...

public Throwable setException( Throwable e ) {
this.exception = e;
}

public Throwable getException() {
return this.exception;
}

public void doAction( int d ) {
if ( d > 2 ) {
// In a normally case we had been probably used throw to pop exception, but it's not
// impossible to handle it under invokation, so...
this.setException("Wrong value");
}
}
}

class D...

public static void main() throws Throwable {
X.getClass().getMethods("doAction", null).invoke( new X(), null );
}
}



It's probably some bit interface beauty and introduce global state, but it's work...

2. Java not completely "eat" all exceptions, it only not handles them so we cannot work with theirs semantics. But if it's not very important to you to handle concrete exceptions but know that execution fails in some method its will be enough for you to handle ExceptionInInitializerError, which Java throws in such cases.

3. Another more radical way to handle such exceptions is - Aspect-Oriented Programming :-)

AOP provides powerful techniques to work with such situations.


pointcut exceptionHandler(Exception e): handler(Exception+) && args(e);

after(Exception e): exceptionHandler(e)
{
ExceptionManager.Publish (e)
}



Read more about AspectJ, and good article about AOP exceptions handling with Spring

Комментариев нет:

Отправить комментарий