At the moment i working with library which can throw hell alot of different exceptions(8-10 per method call) and most of them must be handled, worse of all every method (at any time) can throw AuthenticationExpiredException
, and i must re-attempt to authenticate. For example:
try {
xStream = xSet.createXStream(id, binding, mimeType); //Method call
} catch (AuthenticationExpiredException authenticationExpiredException) {
try {
this.authenticate(); // re-authenticate
xStream = xSet.createXStream(id, binding, mimeType); //Method call again
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob after attempting to re-authenticate",
xamException);
}
} catch (XSystemCorruptException xSystemCorruptException) {
this.entities.clear();
this.closeConnection();
throw new ConnectorException("XSystem was corrupt and connection was closed",
xSystemCorruptException);
} catch (XSetCorruptException xSetCorruptException) {
this.closeEntity(entity);
throw new ConnectorException("XSet for entity: " + entity.getXuid()
+ " was currupt and removed", xSetCorruptException);
} catch (XAMException xamException) {
throw new ConnectorException(
"Error occurred during creating new Blob.", xamException);
}
And this is one of the smallest examples of exception handling. The main question here, is there any way to reduce amount of code which handle exceptions, and make logic cleaner?
Thanks for your feedback. I decided to create separate wrapper for this library by wrapping every method and handling them respectively. To support different handling methods i created interface for wrapper and then implemented it with my custom wrapper like this:
public interface XAMLibraryWrapper{
// Methods
}
/**
* Will attempt to recover before throwing RuntimeException
*/
public class RecoveringXAMLibraryWrapper implements XAMLibraryWrapper{
// Implementation
}
If there is a consistent way to handle those method (i.e. you always wrap them in the same way and re-throw a RuntimeException
, then a custom wrapper library might be the appropriate approach. This can still work when there are 2-3 different ways to handle them (by providing 2-3 wrapper methods (or even classes) for a single wrapped method/class).
Alternatively, if two or more exception types have the exact same handling code, then you can try to look for Java 7 to get multi-catch.
You can use Template method pattern. JdbcTemplate is a wonderful example how this design pattern can simplify exception-heavy code (SQLException
s in this case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With