Reputation: 22267
Too often one sees the following pattern in enterprising Java 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 any other mechanism to "cast" one checked exception type that is not declared in the method header to the one that is. Very often this "try-catch-cast"-block must go into every method of such a class.
I wonder, how to implement an annotation, that catches and converts exceptions?
The using code should then look like this:
@ConvertException(MyException, DbException)
public Something myMethod() throws MyException {
// may throw checked DbException:
Connection c = openDataBase("connectionstring");
// ...
return something;
}
Of course, Maybe one has to write MyException.class
or "MyException"
instead. It should also be possible to chain these annotations, or list multiple exceptions to convert.
My guess is that the annotation would introduce a wrapper function with the catching code block that would call the original function. The annotation would then only have compile-time-retension (and not run-time-retension).
I don't advocate that its wise to do this, it probably isn't because these annotations change the program semantics. It may well be an academical question to "just learn"...
Upvotes: 4
Views: 1270
Reputation: 346260
Yes, this should be possible by creating an annotation processor that uses the compiler tree api (javac.tree
package) to manipulate the source code while it's being compiled.
The problem is of course that this annotation processor now must be present whenever the code is compiled, and many tools that process source code (most prominently IDEs) may not know about it and consider the code invalid.
Upvotes: 0
Reputation: 298838
Annotations don't do anything at all by themselves. You need a tool that evaluates them and does some code changing according to them.
In your case, AspectJ seems to be the best match.
My advice would be to read AspectJ in Action (2nd ed) by Ramnivas Laddad.
As you can see from it's Table of Content, it contains a chapter about exception softening, which is almost exactly what you want.
And since you tagged this question dependency-injection
, assuming you use Spring, here is Spring's own Exception translation mechanism
Upvotes: 3