How to make an exception using Java annotation?

Too often, you see the following pattern in Java initiative programs

public Something myMethod() throws MyException { try { // may throw checked DbException: Connection c = openDataBase("connectionstring"); // ... other code throwing more checked exceptions ... } catch(DbException e) { throw new MyException(e); } return something; } 

... or some other mechanism to "distinguish" one checked type of exception that is not declared in the method header to the one that is. Very often, this "try-catch-cast" -block must be included in every method of such a class.

I wonder how to implement an annotation that catches and transforms exceptions ?

The code used should look like this:

 @ConvertException(MyException, DbException) public Something myMethod() throws MyException { // may throw checked DbException: Connection c = openDataBase("connectionstring"); // ... return something; } 

Of course, maybe you need to write instead of MyException.class or "MyException" . It should also be possible to link these annotations or list a few exceptions for conversion.

I assume that the wrapper function will be introduced in the annotation with a block of catching code that will call the original function. Then the annotation will only contain the time of the compiled time (and not the repetition of the execution time).

I am not saying that itโ€™s wise to do this; itโ€™s probably not because these annotations change the semantics of the program. It may be the academic question of โ€œjust learningโ€ ...

+4
source share
2 answers

Annotations do nothing on their own. You need a tool that evaluates them and performs some code changes according to them.

In your case, AspectJ is best suited.

My advice would be to read AspectJ in action (2nd ed.) By Ramnivas Laddad .

As you can see from it the Table of Contents , it contains a chapter on mitigating decompression, which is almost what you want.

And since you noted this dependency-injection question, assuming you are using Spring, here is Spring's own Exception Mechanism

+3
source

Yes, it should be possible by creating an annotation handler that uses the api compiler tree ( javac.tree package) to control the source code while it compiles.

The problem, of course, is that this annotation handler should now be present whenever code is compiled, and many tools that process the source code (most notably the IDE) may not be aware of this and consider the code invalid.

0
source

All Articles