How to cast an exception via Java annotation? - java

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"...

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

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.

Related

Is it good programming to have a return type of Exception?

I ran into an odd situation during a use case on a project: ESQL is calling a java method, sending it a String input parameter which the method will unmarshal, apply some logic, and then store useful info from the unmarshalled object. So, the method must either throw a JAXBException, or use a try catch in order to handle the possible exceptions.
The problem with this is, that ESQL cannot invoke a java method which includes a throws in the signature. BUT, we want any errors to fall through back to the previously calling MBNode so it can be handled appropriately there, so then trycatch is out of the picture.
It struck me that hey, is it not possible to return a type of Exception when we encounter an issue, and null if not? So I wrote a simple method doing so, and though I didn't get any warnings or errors, it seemed just wrong to me in the sense of good programming.
For example:
public Exception doStuffAndCheckForErorrs(String inString)
{
if(inString.equals(null))
{
return new Exception("Your string is null");
}
else
return null;
}
But I just get a terrible feeling about doing anything this way.
I'm open to any thoughts or different solutions to this, especially if there's a way around the ESQL signature issue.
UPDATE:
Adding reference as to why the ESQL procedure cannot call a java method with a throws clause in the signature.
Excerpt from This link under the CREATE PROCEDURE statement section:
"Any Java method that you want to invoke must have the following basic signature:
public static (< 0 - N parameters>)
where must be in the list of Java IN data types in the table in ESQL to Java data type mapping (excluding the REFERENCE type, which is not permitted as a return value), or the Java void data type. The parameter data types must also be in the ESQL to Java data type mapping table. In addition, the Java method is not allowed to have an exception throws clause in its signature."
This isn't really a question about Java, it's a question about ESQL.
ESQL is able to cope with Java exceptions being thrown through the JNI into ESQL code, you should get a BIP2917 error.
I initially though this might have been an issue with the ESQL method resolver but on IIB v9 I was able to succesfully call the following method:
public static void sayHello() throws Exception{
System.out.println("hello");
}
This makes me think that perhaps you got something else wrong with your ESQL external function/procedure definition?
The point here is you can't DECLARE an exception will be thrown; you can still throw a RuntimeException - without adding a throws clause.
So if you wrap your JAXBException into a RuntimeException, you can throw it and handle according to your requirements, without breaking either requirement. Not sure if I would do that; I would not like to return an exception-type though as it's not meant to be used as a return code.
Be extra sure that this asynch way of handling the issue won't break the ESQL library, as you'll be bypassing part of their code, possibly leaving part of it hanging.
Returning Exception is "quick and dirty". It can be very powerful and useful but this should be avoid if possible.
The invocation in ESQL are made like this for a good reason i won't explained here but you can bypass it by using RuntimeException that does not appears in the method definition.
A use case that specifies throwing an Exception sounds like it may be poorly written.
What is the business or architectural reason for throwing an Exception?
An alternative would be throw a RuntimeException or a custom subclass.
That would allow you to leave it out of the method signature.
Again, the use case seems odd.
The straightforward answer to your question is:
No, it isn't good programming to have a return type of Exception.
The mechanism is meant to happen when something goes wrong, therefore a return type of Exception means that you want to receive the consequence of something that went wrong.
I understand that you can't throw Exception, so you should handle the case with other approach.
The boolean aproach is fine when you want to check up some work: good = return true, bad= return false.
The encapsulation of values in an Object is meant when you want to grab the results of the work: good = return new YourResultObject(val1, val2, ..., valx), bad = return null.
What you can do is use return codes like C programs used to do to report about their states.
Alternatively you can also create an Enum and return the Enum, both are more flexible than the Boolean approach if you want to differentiate between different types of errors
public Enum ReturnCodes {
SUCCESS,
NULLSTRING,
...,
OTHERERROR,
}

Custom RunTime Exceptions

So this is regarding an interview question I was recently asked. The interviewer started on this by asking me how we create our custom Exceptions. On answering that, he asked me how I'd create a RunTimeExceptions. I said we'd create them in the same way as we would create the checked Exceptions. Just our custom exception would extend from the RunTimeException class. Then he asked in what scenarios would you create your own RunTimeException. Now I couldn't think of a good answer to that. In none of my projects, we created custom RunTimeExceptions.
I also think that we should never create RunTimeExceptions. JVM can fail only in a finite number of ways and it handles them well. While writing an application we can't predict what runtime exceptions can occur and hence we shouldn't need to handle them. And if we can predict those conditions, they aren't RunTimeExceptions then. Since we neither need new runtime exceptions, nor need a handling of runtimeexceptions, why would we ever need to create a custom RunTimeException. Everything that we can pre-think of as a possible failure condition should be handled at compile time and it would be a checked exception. Right? Only the things that cannot be handled at compile time and the ones that depend on run time things go into the category of RunTimeExceptions.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException. How do we do that mapping. It doesn't seem possible to me.
Am I missing something/ many things here? Kindly advice.
Thanks,
Chan.
I think the interviewer was trying to see if you understand the purpose of runtime exceptions, which is to signal programmer's errors (as opposed to application exceptions, which signal problems with the execution environment).
You can and you should create subclasses of RuntimeException whenever your method needs to signal a condition that amounts to a programming error, and you need to provide additional information regarding the error the exception describes.
For example, consider a class that lets you store data in a sparse multidimensional array. One of the APIs such class would probably provide is a getter that takes an array of indexes. The number of indexes needs to equal the number of dimensions in the array, and each index must be within its bounds. Supplying an array parameter that has an incorrect number of elements, or has one or more element outside its bounds, is a programming error. You need to signal it with a runtime exception. If you want to signal this error, and provide a full account of what went wrong, your subclass IllegalArgumentException, a subclass of RuntimeException, to build your own exception.
Finally, there is one more situation when you want to subclass RuntimeException: when you should provide a "regular" exception, but you do not want your users to wrap each call of your API in a try/catch block. In situations like these, you can replace a single method
void performOperation() throws CustomApplicationException;
with a pair of methods
boolean canPerformOperation();
void performOperation();
The first method tells the caller that it is safe to call the second method in the current state; it never throws an exception.
The second method fail only in the state when the first method returns false, making a failure a programming error, thus justifying the use of RuntimeException to signal such failures.
Checked Exception vs Unchecked Exception is a long time debate among Java developers. I'm not be here to ignite the fire, but only want to share with you how I use it in our work.
For example, another service call my server for customer information. The input is customerID, and I will return a customer object
// Web Service interface
public CustomerInfo getCustomerInformation(int customerId, int securityToken) {
check(securityToken);
Customer customer = merchantService.getCustomer(customerId);
return customer.getInfo();
}
// MerchantService
public Customer getCustomer(int customerId) {
return customerService.getCustomer(customerId);
}
What will happen if the system can't find a particular customer? Of course it will throw an exception or return null. But returning null is bad, since it will make you check null everytime calling from a service. So I go with throwing exception:
// Customer service
public Customer getCustomer(id) {
Customer customer = getCustomerFromDB();
if (customer == null) throw CustomerNotExistedException();
return customer;
}
Now the question is whether CustomerNotExistedException is a Exception or a RuntimeException. If it's a checked exception, you will need to catch and process it at the function that calls getCustomer. That means you must catch it at MerchantService. However, all you want is to produce a 404 error at WebService level, so that catching it at MerchantService won't do anything more than throwing the exception again. It pollutes the code.
In the general case, I often use RuntimeException to let some exception "bubble up" to the level in which they can be processed.
For your reference, I would recommend the book Clean code from Robert C. Martin. It explains quite well how we should use exception to handle errors in Java.
You would create your own RuntimeException subclass if:
You don't want it to be a checked exception, because you don't expect callers to explicitly catch the exception. (Personally I believe that checked exceptions are rather overused in the standard library.)
You still want to provide more information than just a message (just the type itself is a helpful starting point in a log).
HibernateException is an example of this in the Hibernate ORM.
I think when you are creating Custom Exceptions , please don't subclass RuntimeException , it defeats the whole purpose of creating the custom exception.
Even if we write custom RunTimeExceptions and then a custom method that should throw that RunTimeException - how do we make sure that the method will throw that particular RunTimeException.
The point here is actually the caller of the method needn't surround that in a try-catch block as it is not a checked exception. Unless you have a good reason to throw a custom unchecked exception , say , just to provide additional custom information for logging etc. don't do that. Another bad implementation will be sometimes you would to just want to catch the checked exceptions in your code and throw custom unchecked exceptions to get rid of all the try-catch in the caller code.

What's the best to handle unaccepted method arguments in Java?

When writing a method, say, inside one of your DAO objects, and you dont want this method to accept certain input, for discussions sake, say it does not allow null arguments. How do you go about implementing that, taking into account this method is likely to be reused in the future by new team members.
The way I do it is:
In the interface, I document inside the method javadoc that arguments a, b and c cannot be null.
Inside the method I check for null values first thing, and if any of a, b or c are null then I throw an IllegalArgumentException.
But, what if some developer in the future just reads off the method signature and decides that it what he/she needs and starts using it, without paying attention to this detail, and worse testing does not reveal it. NULL pointer exception won't occur and we are getting a useful error message, but we are still getting an error in production that could've been avoided.
Is there a way to enforce this at compile time? I doubt it, but what would be the safest and most bad-developer-proof way to go about doing this?
I don't think you can enforce this compile time, but you can certainly make the method signatures easy to understand.
If you don't mine adding a dependency on one of the validations frameworks you can use JSR 303's #NotNull or similar tools like Preconditions.
With JSR 303 you can do suff like:
#NotNull
#Size(min = 2, max = 14)
#UpperCase
private String licensePlate;
or
#NotNull
#NotEmpty
public String foo(#NotNull #Pattern(regexp="[0-9]") String param) {
...
}
Have a look at the Getting started with JSR 303 Bean Validation for more comprehensive examples.
You can use jsr305 with static code check tools like findbugs to check it before commit/release.
public String method(#NonNull String parameter ){
...
}
findbugs manual on annotation
As closest as you can get in enforcing things at compile time is by throwing checked exceptions which will force the caller to handle the exception at compile time. This might make them read the doc. The IllegalArgumentException is unchecked and can go unnoticed.
Normal practice in safeguarding on unusable values is by returning at the point we identify something unusable and add an error message for display. This will prevent the exception on production that might happen if the execution continued in that method, but might not altogether avoid it.

Approaches for simplifying try / catch in Java

I'm looking for ways to simplify lots of ugly try catch code all over the place. For instance I'm seeing:
try {
objectA.setFieldX(objectB.getFieldY());
}
catch(NullPointerException e) {
...stuff
}
catch(OtherException e) {
...stuff
}
This kind of thing is repeated all over the place for the various fields, some are slightly different in behavior based on if the field is optional or not.
It is bulky, poorly documented, and leaves the reader with the distinct impression that (aside from being poor code) it might be wrong.
If my DataTransferObejcts had (in addition to the standard set(value) and get()) "generic" get and set methods that took some kind of enumerated FieldID (like get(), or set(, object value)- then (in the class with many sets, wrapped in ugly try/catches) I could simply define some helpers like:
setRequiredField(objSource, <FieldIDsource>, objDest, <FieldIDdest) {
object SourceField = objSource.get(<FieldIDsource>);
if (sourceField != null) {
try {
objDest.set(<FieldIDdest>, SourceField);
}
catch (OtherException) {
... stuff (like logging) here
}
}
else {
... stuff (like logging) here
}
}
Then the method doing all the sets would have code like:
setRequiredField(source, <FieldIDAsource>, dest, <FieldIDAdest>);
setOptionalField(source, <FieldIDBsource>, dest, <FieldIDBdest>);
It becomes a lot less bulky, more readable, more correct....
...but there are some issues like:
1) casting up the wazoo: In the generic methods (in the Data Transfer Objects) I'd need to do a lot of casting.
2) making the generic methods complete/correct: I suppose using an Enum I could lock things up somewhat but there is a worry of making some mistake in the generic methods (makes me want to "generate" the Data Transfer Objects with something like FreeMarker- but they have some "domain logic" in them...).
Anyway, if someone has some pointers how to do this right I'd like to know
Actually, this is a clear example of something that can be solved via Aspect Oriented Programming (AOP). The idea is you can inject standard logic for issues that cut across your whole application. Classic examples are error handling and logging. There are several ways to do AOP with Java including Spring and AspectJ. See http://www.voelter.de/data/articles/aop/aop.html for more information.
You should refer the following thread in stack overflow
When to choose checked and unchecked exceptions
The main idea is to only catch exception with which you can do something more. Otherwise you should let the exception propagate to the last layer and only catch Exception there directly before logging it.
If I understand your problem you are trying to copy properties from one bean to another. You may consider using dozer for that...

In Java how would you write the equivalent of Iterable which could throw exceptions?

In java a class can implement Iterable which lets you use the foreach() statement and the iteration syntatic sugar:
for(T t:ts) ...
However, this does not allow you to throw exceptions on the construction for an Iterator. If you were iterating off a network, file, database etc it would be nice to be able to throw exceptions. Obvious candidates are java.io.InputStream, Reader and the java.nio.Channel code, but none of this can use Generics like the Iterable interface can.
Is there a common idiom or Java API for this situation?
Clarification: This is asking if there is a pattern or alternative interface for iterating for objects off a non-memory source. As responders have said, just throwing RuntimeExceptions to get around the problem is not recommended or what I was looking for.
Edit 2: Thanks to answers so far. The consensus seems to be "you can't". So can I extend the question to "What do you do in this situation, when this situation would be useful?" Just write your own interface?
Unfortunately you can't. There are two problems:
The Iterator API doesn't declare any exceptions to be thrown, so you'd have to throw RuntimeExceptions (or non-Exception throwables)
The enhanced for loop doesn't do anything to try to release resources at the end of the loop
This is very annoying. In C#, for instance, you can really easily write code to iterate through the lines of a text file:
public static IEnumerable<string> ReadLines(string filename)
{
using (TextReader reader = File.OpenText(filename))
{
string line;
while ( (line=reader.ReadLine()) != null)
{
yield return line;
}
}
}
Use as:
foreach (string line in ReadLines("foo.txt"))
The foreach loop calls Dispose on the IEnumerator in a finally block, which translates to "check if we need to do anything in the iterator block's finally (from the using statement)". Obviously there are no checked exceptions in C#, so that side of things isn't a problem either.
A whole (useful!) idiom is pretty much unworkable in Java due to this.
Streams like a network aren't really iterable in the traditional sense. Data can come through at any time, so it doesn't make sense to have a for each loop.
For a file read, or a DB snapshot (like a select query) there's no reason you can't take that data, segment it into logical chunks and implement an iterable interface.
You can also call an initialize method first that will catch any exceptions, if that's an issue.
try{
ts.initializeIOIterator();
}catch(...)
for(T t:ts)
...
Best what you can do is to create RuntimeIOException which you will throw from your hasNext/next implementation in case of errors.
try {
for (...) {
// do my stuff here
}
catch (RuntimeIOException e) {
throw e.getCause(); // rethrow IOException
}
RuntimeIOException will be runtime exception, wrapping your IOException:
class RuntimeIOException extends RuntimeException {
RuntimeIOException(IOException e) {
super(e);
}
IOException getCause() {
return (IOException) super.getCause();
}
}
Sometimes there is no other way.
I'd say you can't, even if you could you probably shouldn't. You get bytes from these things, if they were used in a for loop likely every byte would end up boxed.
What you can do is wrap checked exceptions in unchecked exceptions and comply to the iterable interface, though again this isn't advisable.
Generally in this situation, I would throw an appropriate subclass of RuntimeException in the Iterable's implementation.
In terms of cleaning up resources, a try - finally block works just as well wrapping a foreach block as it does around any other bit of code, so from the client's perspective it can easily use this to clean up any resources. If you want to manage resources within the Iterable it can be trickier, since there's no obvious start and finish lifecycle points.
In this case the best you could probably do is to create the resources on demand (i.e. the first call to next()), and then destroy them either when a call to next() is about to return false, or when an exception is thrown in the body of next(). Doing this would of course mean that when your next() method exits with an exception, the iterator can no longer be used - this is not an unreasonable constraint to place (consider the exception a more error-y version of returning false) but is something you should document as this isn't strictly covered by the interface.
That said, the above assumes that you're creating something solely as an Iterable. I find that in practice, when I implement Iterable on a class, it's more like a "super-getter" (i.e. a way for clients to conveniently access the information stored within it), than it is the point of the class itself. Most of the time these objects will be set up independently and accessed via other methods, so their lifecycle can be managed completely separately from their existence as an Iterable.
This might seem tangential to the question, but the immediate answer to the question is straightforward ("use runtime exceptions") - the tricky part is maintaining an appropriate state in the presence of these exceptions.

Categories

Resources